import { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { membersAPI } from '../services/api';
import { useAuthStore } from '../stores/authStore';

const initialInviteForm = {
  roll_no: '',
  email: '',
  phone: '',
};

export default function Members() {
  const { user } = useAuthStore();
  const [members, setMembers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(1);
  const [search, setSearch] = useState('');
  const [activeTab, setActiveTab] = useState('all');
  const [pagination, setPagination] = useState({
    page: 1,
    total: 0,
    total_pages: 1,
    has_next: false,
    has_previous: false,
  });
  const [showInviteForm, setShowInviteForm] = useState(false);
  const [inviteForm, setInviteForm] = useState(initialInviteForm);
  const [inviteLoading, setInviteLoading] = useState(false);
  const [inviteError, setInviteError] = useState('');
  const [inviteResult, setInviteResult] = useState(null);

  useEffect(() => {
    const fetchMembers = async () => {
      setLoading(true);
      try {
        const status = activeTab === 'deceased' ? 'deceased' : '';
        const response = await membersAPI.list(page, 20, search, status);
        setMembers(response.members || []);
        setPagination({
          page: response.page || 1,
          total: response.total || 0,
          total_pages: response.total_pages || 1,
          has_next: !!response.has_next,
          has_previous: !!response.has_previous,
        });
      } catch (error) {
        console.error('Failed to fetch members:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchMembers();
  }, [page, search, activeTab]);

  const handleInviteChange = (event) => {
    const { name, value } = event.target;
    setInviteForm((current) => ({
      ...current,
      [name]: value,
    }));
  };

  const handleSendInvitation = async (event) => {
    event.preventDefault();
    setInviteLoading(true);
    setInviteError('');
    setInviteResult(null);

    try {
      const response = await membersAPI.sendInvitation(inviteForm);
      setInviteResult(response);
      setInviteForm(initialInviteForm);
    } catch (error) {
      setInviteError(error.response?.data?.error || 'Failed to send invitation.');
    } finally {
      setInviteLoading(false);
    }
  };

  return (
    <div>
      <div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between mb-6">
        <div>
          <h1 className="text-3xl font-bold text-gray-800">Members</h1>
          <p className="text-sm text-slate-500 mt-1">
            Browse all members or switch to deceased members for the annual dashboard and age filters.
          </p>
        </div>

        <div className="flex flex-wrap gap-3 items-center">
          {user?.role === 'admin' && (
            <button
              type="button"
              onClick={() => {
                setShowInviteForm((current) => !current);
                setInviteError('');
                setInviteResult(null);
              }}
              className="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700"
            >
              {showInviteForm ? 'Close Invitation' : 'Send Invitation'}
            </button>
          )}
          <Link
            to="/deceased-members"
            className="inline-flex items-center rounded-2xl border border-slate-300 bg-white px-4 py-2 text-sm font-medium text-slate-700 transition hover:border-slate-400 hover:bg-slate-50"
          >
            Deceased Dashboard
          </Link>
        </div>
      </div>

      <div className="mb-6 flex flex-wrap gap-3">
        <button
          type="button"
          onClick={() => {
            setActiveTab('all');
            setPage(1);
          }}
          className={`rounded-2xl px-4 py-2 text-sm font-semibold transition ${
            activeTab === 'all'
              ? 'bg-slate-900 text-white'
              : 'bg-slate-100 text-slate-700 hover:bg-slate-200'
          }`}
        >
          All Members
        </button>
        <button
          type="button"
          onClick={() => {
            setActiveTab('deceased');
            setPage(1);
          }}
          className={`rounded-2xl px-4 py-2 text-sm font-semibold transition ${
            activeTab === 'deceased'
              ? 'bg-slate-900 text-white'
              : 'bg-slate-100 text-slate-700 hover:bg-slate-200'
          }`}
        >
          Deceased Members
        </button>
      </div>

      {showInviteForm && user?.role === 'admin' && (
        <form onSubmit={handleSendInvitation} className="bg-white rounded-lg shadow p-6 mb-6">
          <h2 className="text-xl font-semibold text-gray-800 mb-4">Invite Member</h2>

          {inviteError && (
            <div className="mb-4 rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-red-700">
              {inviteError}
            </div>
          )}

          {inviteResult && (
            <div className="mb-4 rounded-lg border border-green-200 bg-green-50 px-4 py-3 text-green-700">
              <p>{inviteResult.message}</p>
              <p className="mt-2 break-all">
                Invitation link: <span className="font-semibold">{inviteResult.invitation_url}</span>
              </p>
            </div>
          )}

          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <FormField
              label="Roll Number"
              name="roll_no"
              value={inviteForm.roll_no}
              onChange={handleInviteChange}
              required
            />
            <FormField
              label="Email"
              name="email"
              type="email"
              value={inviteForm.email}
              onChange={handleInviteChange}
              required
            />
            <FormField
              label="Phone"
              name="phone"
              value={inviteForm.phone}
              onChange={handleInviteChange}
              required
            />
          </div>

          <div className="mt-4 flex gap-3">
            <button
              type="submit"
              disabled={inviteLoading}
              className="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700 disabled:opacity-50"
            >
              {inviteLoading ? 'Sending...' : 'Send Invitation'}
            </button>
          </div>
        </form>
      )}

      <div className="mb-4">
        <input
          type="text"
          placeholder="Search members..."
          value={search}
          onChange={(e) => {
            setSearch(e.target.value);
            setPage(1);
          }}
          className="w-full px-4 py-2 border border-gray-300 rounded-lg"
        />
      </div>

      {!loading && (
        <div className="mb-4 flex flex-col gap-2 text-sm text-gray-600 md:flex-row md:items-center md:justify-between">
          <p>
            Showing page {pagination.page} of {pagination.total_pages} with {pagination.total.toLocaleString()} members
          </p>
          <div className="flex gap-2">
            <button
              type="button"
              onClick={() => setPage((current) => Math.max(1, current - 1))}
              disabled={!pagination.has_previous}
              className="rounded border border-gray-300 px-3 py-2 text-gray-700 disabled:cursor-not-allowed disabled:opacity-50"
            >
              Previous
            </button>
            <button
              type="button"
              onClick={() => setPage((current) => current + 1)}
              disabled={!pagination.has_next}
              className="rounded border border-gray-300 px-3 py-2 text-gray-700 disabled:cursor-not-allowed disabled:opacity-50"
            >
              Next
            </button>
          </div>
        </div>
      )}

      {loading && <p className="text-gray-600">Loading...</p>}

      {!loading && (
        <div className="space-y-4">
          {members.length === 0 && (
            <div className="rounded-[28px] bg-white p-8 text-center text-gray-600 shadow-[0_20px_50px_rgba(15,23,42,0.08)]">
              No members found
            </div>
          )}

          {members.map((member) => (
            <div
              key={member.id}
              className="overflow-hidden rounded-[28px] border border-slate-200/70 bg-white shadow-[0_20px_50px_rgba(15,23,42,0.08)]"
            >
              <div className="bg-[linear-gradient(135deg,rgba(8,145,178,0.1),rgba(15,23,42,0.04))] px-5 py-4">
                <div className="flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
                  <div>
                    <p className="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">
                      Roll No {member.roll_no || '-'}
                    </p>
                    <h2 className="mt-2 text-xl font-semibold text-slate-900">{member.full_name}</h2>
                  </div>

                  <span
                    className={`inline-flex self-start rounded-full px-3 py-1 text-xs font-semibold ${
                      member.status === 'active'
                        ? 'bg-green-100 text-green-800'
                        : 'bg-red-100 text-red-800'
                    }`}
                  >
                    {member.status || 'unknown'}
                  </span>
                </div>
              </div>

              <div className="grid gap-4 px-5 py-5 md:grid-cols-[1fr_auto] md:items-end">
                <div className="grid gap-3 sm:grid-cols-2">
                  <MemberInfo label="Email" value={member.email || '-'} />
                  <MemberInfo label="Phone" value={member.phone || '-'} />
                </div>

                <div className="flex justify-start md:justify-end">
                  <Link
                    to={`/members/${member.id}`}
                    className="inline-flex rounded-2xl bg-slate-900 px-4 py-2.5 text-sm font-medium text-white transition hover:bg-slate-800"
                  >
                    View Member
                  </Link>
                </div>
              </div>
            </div>
          ))}

          {members.length > 0 && (
            <div className="flex flex-col gap-3 rounded-[24px] bg-white px-5 py-4 shadow-[0_18px_48px_rgba(15,23,42,0.08)] sm:flex-row sm:items-center sm:justify-between">
              <p className="text-sm text-slate-500">
                Page {pagination.page} of {pagination.total_pages}
              </p>
              <div className="flex gap-2">
                <button
                  type="button"
                  onClick={() => setPage((current) => Math.max(1, current - 1))}
                  disabled={!pagination.has_previous}
                  className="rounded-2xl border border-slate-200 px-4 py-2 text-sm font-medium text-slate-700 transition hover:bg-slate-50 disabled:cursor-not-allowed disabled:opacity-50"
                >
                  Previous
                </button>
                <button
                  type="button"
                  onClick={() => setPage((current) => current + 1)}
                  disabled={!pagination.has_next}
                  className="rounded-2xl bg-slate-900 px-4 py-2 text-sm font-medium text-white transition hover:bg-slate-800 disabled:cursor-not-allowed disabled:opacity-50"
                >
                  Next
                </button>
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

function MemberInfo({ label, value }) {
  return (
    <div className="rounded-2xl bg-slate-50 px-4 py-3">
      <p className="text-xs font-semibold uppercase tracking-[0.16em] text-slate-400">{label}</p>
      <p className="mt-1 text-sm font-medium text-slate-700">{value}</p>
    </div>
  );
}

function FormField({ label, name, value, onChange, type = 'text', required = false }) {
  return (
    <div>
      <label className="block text-sm font-medium text-gray-700 mb-2">{label}</label>
      <input
        type={type}
        name={name}
        value={value}
        onChange={onChange}
        required={required}
        className="w-full rounded-lg border border-gray-300 px-4 py-2 focus:outline-none focus:ring-2 focus:ring-blue-600"
      />
    </div>
  );
}
