import { useState } from 'react';
import { useParams } from 'react-router-dom';
import { useOrgMembers, useRemoveOrgMember, useUpdateOrgMember } from '../../hooks/useClients';
import { InviteMemberModal } from './InviteMemberModal';
import type { OrgRole } from '../../types/api';

const ROLE_LABELS: Record<OrgRole, string> = {
  owner: 'Owner',
  admin: 'Admin',
  manager: 'Manager',
  member: 'Member',
  viewer: 'Viewer',
};

const ROLE_COLORS: Record<OrgRole, string> = {
  owner: 'bg-purple-100 text-purple-700',
  admin: 'bg-red-100 text-red-700',
  manager: 'bg-indigo-100 text-indigo-700',
  member: 'bg-green-100 text-green-700',
  viewer: 'bg-gray-100 text-gray-600',
};

export function OrgMembersPage() {
  const { orgSlug } = useParams<{ orgSlug: string }>();
  const orgId = orgSlug ?? '';
  const { data: members = [], isLoading, error } = useOrgMembers(orgId);
  const removeMember = useRemoveOrgMember(orgId);
  const updateMember = useUpdateOrgMember(orgId);
  const [showInvite, setShowInvite] = useState(false);
  const [search, setSearch] = useState('');

  const filtered = members.filter(
    (m) =>
      m.full_name.toLowerCase().includes(search.toLowerCase()) ||
      m.email.toLowerCase().includes(search.toLowerCase()),
  );

  if (isLoading) return <div className="text-gray-400 py-8 text-center">Loading…</div>;
  if (error) return <div className="text-red-600 py-4">Failed to load members.</div>;

  return (
    <div>
      <div className="flex items-center justify-between mb-4">
        <input
          type="search"
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          placeholder="Search members…"
          className="border border-gray-200 rounded-lg px-3 py-1.5 text-sm w-64 focus:outline-none focus:ring-2 focus:ring-indigo-400"
        />
        <button
          onClick={() => setShowInvite(true)}
          className="bg-indigo-600 hover:bg-indigo-700 text-white text-sm font-medium px-4 py-2 rounded-lg transition-colors"
        >
          Invite member
        </button>
      </div>

      <div className="bg-white rounded-lg border border-gray-200 overflow-hidden">
        <table className="w-full text-sm">
          <thead className="bg-gray-50 border-b border-gray-200">
            <tr>
              <th className="text-left px-4 py-3 font-medium text-gray-600">Member</th>
              <th className="text-left px-4 py-3 font-medium text-gray-600">Role</th>
              <th className="text-left px-4 py-3 font-medium text-gray-600">Added</th>
              <th className="px-4 py-3" />
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-100">
            {filtered.length === 0 && (
              <tr>
                <td colSpan={4} className="px-4 py-8 text-center text-gray-400">
                  {search ? 'No members match your search.' : 'No members yet. Invite someone!'}
                </td>
              </tr>
            )}
            {filtered.map((member) => (
              <tr key={member.membership_id} className="hover:bg-gray-50">
                <td className="px-4 py-3">
                  <div className="font-medium text-gray-900">{member.full_name}</div>
                  <div className="text-xs text-gray-500">{member.email}</div>
                </td>
                <td className="px-4 py-3">
                  <select
                    value={member.role_in_org}
                    onChange={(e) =>
                      updateMember.mutate({ userId: member.user_id, data: { role_in_org: e.target.value as OrgRole } })
                    }
                    disabled={member.role_in_org === 'owner'}
                    className={`text-xs font-medium px-2 py-1 rounded-full border-0 cursor-pointer ${ROLE_COLORS[member.role_in_org]}`}
                  >
                    {Object.entries(ROLE_LABELS)
                      .filter(([r]) => r !== 'owner')
                      .map(([value, label]) => (
                        <option key={value} value={value}>{label}</option>
                      ))}
                    {member.role_in_org === 'owner' && <option value="owner">Owner</option>}
                  </select>
                </td>
                <td className="px-4 py-3 text-gray-500 text-xs">
                  {member.created_at ? new Date(member.created_at).toLocaleDateString() : '—'}
                </td>
                <td className="px-4 py-3 text-right">
                  {member.role_in_org !== 'owner' && (
                    <button
                      onClick={() => {
                        if (confirm(`Remove ${member.full_name} from this organization?`)) {
                          removeMember.mutate(member.user_id);
                        }
                      }}
                      className="text-xs text-red-500 hover:text-red-700"
                    >
                      Remove
                    </button>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {showInvite && (
        <InviteMemberModal orgId={orgId} onClose={() => setShowInvite(false)} />
      )}
    </div>
  );
}
