'use client';

import { useState } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { Loader2, Mail, RotateCw, Plus, Trash2 } from 'lucide-react';
import { toast } from 'sonner';

import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import { Sheet, SheetContent, SheetFooter, SheetHeader, SheetTitle } from '@/components/ui/sheet';
import { ConfirmationDialog } from '@/components/shared/confirmation-dialog';
import { apiFetch } from '@/lib/api/client';
import { toastError } from '@/lib/api/toast-error';

interface Invite {
  id: string;
  email: string;
  name: string | null;
  isSuperAdmin: boolean;
  expiresAt: string;
  usedAt: string | null;
  createdAt: string;
  status: 'pending' | 'accepted' | 'expired';
}

const STATUS_STYLES: Record<Invite['status'], string> = {
  pending: 'bg-amber-100 text-amber-800 border-amber-200',
  accepted: 'bg-green-100 text-green-800 border-green-200',
  expired: 'bg-muted text-muted-foreground border-muted',
};

export function InvitationsManager() {
  const qc = useQueryClient();
  const [sheetOpen, setSheetOpen] = useState(false);
  const [email, setEmail] = useState('');
  const [name, setName] = useState('');
  const [isSuperAdmin, setIsSuperAdmin] = useState(false);

  const { data: invites = [], isLoading } = useQuery<Invite[]>({
    queryKey: ['admin', 'invitations'],
    queryFn: () => apiFetch<{ data: Invite[] }>('/api/v1/admin/invitations').then((r) => r.data),
  });

  const createMutation = useMutation({
    mutationFn: () =>
      apiFetch('/api/v1/admin/invitations', {
        method: 'POST',
        body: { email, name: name || undefined, isSuperAdmin },
      }),
    onSuccess: () => {
      toast.success(`Invite sent to ${email}`);
      setSheetOpen(false);
      setEmail('');
      setName('');
      setIsSuperAdmin(false);
      qc.invalidateQueries({ queryKey: ['admin', 'invitations'] });
    },
    onError: (err) => toastError(err),
  });

  const resendMutation = useMutation({
    mutationFn: (id: string) =>
      apiFetch(`/api/v1/admin/invitations/${id}/resend`, { method: 'POST' }),
    onSuccess: () => {
      toast.success('Invite resent');
      qc.invalidateQueries({ queryKey: ['admin', 'invitations'] });
    },
    onError: (err) => toastError(err),
  });

  const revokeMutation = useMutation({
    mutationFn: (id: string) => apiFetch(`/api/v1/admin/invitations/${id}`, { method: 'DELETE' }),
    onSuccess: () => {
      toast.success('Invite revoked');
      qc.invalidateQueries({ queryKey: ['admin', 'invitations'] });
    },
    onError: (err) => toastError(err),
  });

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-lg font-semibold">Pending invitations</h2>
          <p className="text-sm text-muted-foreground">
            Invitations expire 72 hours after issue. Resending mints a new token and emails it.
          </p>
        </div>
        <Button onClick={() => setSheetOpen(true)}>
          <Plus className="h-4 w-4 mr-1.5" aria-hidden />
          Send invite
        </Button>
      </div>

      {isLoading ? (
        <p className="text-sm text-muted-foreground">Loading…</p>
      ) : invites.length === 0 ? (
        <div className="rounded-lg border border-dashed p-8 text-center text-muted-foreground">
          <Mail className="mx-auto h-6 w-6 mb-2" aria-hidden />
          <p className="text-sm">No invitations issued yet.</p>
        </div>
      ) : (
        <div className="rounded-lg border bg-card overflow-hidden">
          <table className="w-full text-sm">
            <thead className="bg-muted/40 text-xs text-muted-foreground">
              <tr>
                <th className="text-left font-medium px-3 py-2">Email</th>
                <th className="text-left font-medium px-3 py-2">Name</th>
                <th className="text-left font-medium px-3 py-2">Role</th>
                <th className="text-left font-medium px-3 py-2">Status</th>
                <th className="text-left font-medium px-3 py-2">Expires</th>
                <th className="px-3 py-2">
                  <span className="sr-only">Actions</span>
                </th>
              </tr>
            </thead>
            <tbody>
              {invites.map((i) => (
                <tr key={i.id} className="border-t">
                  <td className="px-3 py-2 font-medium">{i.email}</td>
                  <td className="px-3 py-2 text-muted-foreground">{i.name ?? '-'}</td>
                  <td className="px-3 py-2 text-muted-foreground">
                    {i.isSuperAdmin ? 'Super admin' : 'Standard user'}
                  </td>
                  <td className="px-3 py-2">
                    <span
                      className={`inline-flex items-center rounded-full border px-2 py-0.5 text-xs font-medium capitalize ${STATUS_STYLES[i.status]}`}
                    >
                      {i.status}
                    </span>
                  </td>
                  <td className="px-3 py-2 text-muted-foreground">
                    {new Date(i.expiresAt).toLocaleString()}
                  </td>
                  <td className="px-3 py-2 text-right">
                    {i.status === 'pending' || i.status === 'expired' ? (
                      <div className="inline-flex items-center gap-1">
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={() => resendMutation.mutate(i.id)}
                          disabled={resendMutation.isPending || !!i.usedAt}
                          title="Resend invite"
                        >
                          <RotateCw className="h-3.5 w-3.5" aria-hidden />
                        </Button>
                        {i.status === 'pending' && (
                          <ConfirmationDialog
                            trigger={
                              <Button
                                variant="ghost"
                                size="icon"
                                className="text-destructive"
                                title="Revoke"
                              >
                                <Trash2 className="h-3.5 w-3.5" aria-hidden />
                              </Button>
                            }
                            title="Revoke invitation?"
                            description={`Revoke the pending invitation for ${i.email}? The link in the email will stop working.`}
                            confirmLabel="Revoke"
                            onConfirm={() => revokeMutation.mutate(i.id)}
                          />
                        )}
                      </div>
                    ) : (
                      <span className="text-xs text-muted-foreground">-</span>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      <Sheet open={sheetOpen} onOpenChange={setSheetOpen}>
        <SheetContent>
          <SheetHeader>
            <SheetTitle>Send invitation</SheetTitle>
          </SheetHeader>
          <form
            className="mt-6 space-y-4"
            onSubmit={(e) => {
              e.preventDefault();
              createMutation.mutate();
            }}
          >
            <div className="space-y-1.5">
              <Label htmlFor="invite-email">Email *</Label>
              <Input
                id="invite-email"
                type="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                required
              />
            </div>
            <div className="space-y-1.5">
              <Label htmlFor="invite-name">Display name</Label>
              <Input
                id="invite-name"
                value={name}
                onChange={(e) => setName(e.target.value)}
                placeholder="Optional"
              />
            </div>
            <div className="flex items-start justify-between gap-4 rounded-lg border p-3">
              <div>
                <Label htmlFor="invite-superadmin" className="text-sm font-medium">
                  Grant super admin
                </Label>
                <p className="text-xs text-muted-foreground">
                  Super admins bypass per-port permission checks. Use sparingly.
                </p>
              </div>
              <Switch
                id="invite-superadmin"
                checked={isSuperAdmin}
                onCheckedChange={setIsSuperAdmin}
              />
            </div>
            <SheetFooter>
              <Button
                type="button"
                variant="outline"
                onClick={() => setSheetOpen(false)}
                disabled={createMutation.isPending}
              >
                Cancel
              </Button>
              <Button type="submit" disabled={!email.trim() || createMutation.isPending}>
                {createMutation.isPending && (
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" aria-hidden />
                )}
                Send invite
              </Button>
            </SheetFooter>
          </form>
        </SheetContent>
      </Sheet>
    </div>
  );
}
