import { useState } from 'react';
import { useParams } from 'react-router-dom';
import { useInvitations, useRevokeInvitation } from '../../hooks/useClients';
import { InviteMemberModal } from './InviteMemberModal';
import type { Invitation } from '../../types/api';

function statusLabel(inv: Invitation) {
  if (inv.is_accepted) return { label: 'Accepted', cls: 'bg-green-100 text-green-700' };
  if (inv.is_revoked) return { label: 'Revoked', cls: 'bg-red-100 text-red-700' };
  if (inv.is_expired) return { label: 'Expired', cls: 'bg-gray-100 text-gray-500' };
  return { label: 'Pending', cls: 'bg-yellow-100 text-yellow-700' };
}

export function OrgInvitationsPage() {
  const { orgSlug } = useParams<{ orgSlug: string }>();
  const orgId = orgSlug ?? '';
  const { data: invitations = [], isLoading } = useInvitations(orgId);
  const revoke = useRevokeInvitation(orgId);
  const [showInvite, setShowInvite] = useState(false);

  if (isLoading) return <div className="text-gray-400 py-8 text-center">Loading…</div>;

  return (
    <div>
      <div className="flex justify-end mb-4">
        <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">Email</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">Expires</th>
              <th className="text-left px-4 py-3 font-medium text-gray-600">Status</th>
              <th className="px-4 py-3" />
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-100">
            {invitations.length === 0 && (
              <tr>
                <td colSpan={5} className="px-4 py-8 text-center text-gray-400">No invitations yet.</td>
              </tr>
            )}
            {invitations.map((inv) => {
              const { label, cls } = statusLabel(inv);
              return (
                <tr key={inv.id} className="hover:bg-gray-50">
                  <td className="px-4 py-3 font-medium text-gray-800">{inv.email}</td>
                  <td className="px-4 py-3 capitalize text-gray-600">{inv.role_in_org}</td>
                  <td className="px-4 py-3 text-gray-500 text-xs">
                    {new Date(inv.expires_at).toLocaleDateString()}
                  </td>
                  <td className="px-4 py-3">
                    <span className={`text-xs font-medium px-2 py-0.5 rounded-full ${cls}`}>{label}</span>
                  </td>
                  <td className="px-4 py-3 text-right">
                    {!inv.is_accepted && !inv.is_revoked && !inv.is_expired && (
                      <button
                        onClick={() => {
                          if (confirm(`Revoke invitation for ${inv.email}?`)) {
                            revoke.mutate(inv.id);
                          }
                        }}
                        className="text-xs text-red-500 hover:text-red-700"
                      >
                        Revoke
                      </button>
                    )}
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

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