'use client';

import { useState } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { format } from 'date-fns';
import { Pencil, Plus, Trash2 } from 'lucide-react';
import { toast } from 'sonner';

import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { ConfirmationDialog } from '@/components/shared/confirmation-dialog';
import { PageHeader } from '@/components/shared/page-header';
import { apiFetch } from '@/lib/api/client';
import { toastError } from '@/lib/api/toast-error';
import type { FormField } from '@/lib/validators/form-templates';
import { FormTemplateForm } from './form-template-form';

export interface FormTemplate {
  id: string;
  name: string;
  description: string | null;
  fields: FormField[];
  isActive: boolean;
  updatedAt: string;
}

export function FormTemplateList() {
  const qc = useQueryClient();
  const [formOpen, setFormOpen] = useState(false);
  const [editing, setEditing] = useState<FormTemplate | null>(null);

  const { data: templates = [], isLoading } = useQuery<FormTemplate[]>({
    queryKey: ['admin', 'form-templates'],
    queryFn: () =>
      apiFetch<{ data: FormTemplate[] }>('/api/v1/admin/form-templates').then((r) => r.data),
  });

  const deleteMutation = useMutation({
    mutationFn: (id: string) =>
      apiFetch(`/api/v1/admin/form-templates/${id}`, { method: 'DELETE' }),
    onSuccess: () => {
      toast.success('Template deleted');
      qc.invalidateQueries({ queryKey: ['admin', 'form-templates'] });
    },
    onError: (err) => toastError(err),
  });

  return (
    <div>
      <PageHeader
        title="Form Templates"
        description="Public intake forms for clients (residential inquiries, EOI supplements, etc.)"
        actions={
          <Button
            onClick={() => {
              setEditing(null);
              setFormOpen(true);
            }}
          >
            <Plus className="h-4 w-4 mr-1.5" aria-hidden />
            New template
          </Button>
        }
      />

      {isLoading ? (
        <p className="text-sm text-muted-foreground">Loading…</p>
      ) : templates.length === 0 ? (
        <div className="rounded-lg border border-dashed p-8 text-center text-muted-foreground">
          <p className="text-sm">No form templates yet.</p>
        </div>
      ) : (
        <div className="rounded-lg border divide-y">
          {templates.map((t) => (
            <div key={t.id} className="flex items-center gap-3 p-3">
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-2">
                  <span className="text-sm font-medium">{t.name}</span>
                  {!t.isActive && (
                    <Badge variant="outline" className="text-xs">
                      Inactive
                    </Badge>
                  )}
                </div>
                <div className="text-xs text-muted-foreground">
                  {t.fields.length} field{t.fields.length === 1 ? '' : 's'} · updated{' '}
                  {format(new Date(t.updatedAt), 'MMM d, yyyy')}
                </div>
              </div>
              <Button
                variant="ghost"
                size="icon"
                aria-label="Edit form template"
                onClick={() => {
                  setEditing(t);
                  setFormOpen(true);
                }}
              >
                <Pencil className="h-4 w-4" aria-hidden />
              </Button>
              <ConfirmationDialog
                trigger={
                  <Button
                    variant="ghost"
                    size="icon"
                    className="text-destructive"
                    aria-label="Delete form template"
                  >
                    <Trash2 className="h-4 w-4" aria-hidden />
                  </Button>
                }
                title="Delete form template"
                description={`Delete "${t.name}"? Existing submissions will be preserved.`}
                confirmLabel="Delete"
                onConfirm={() => deleteMutation.mutate(t.id)}
              />
            </div>
          ))}
        </div>
      )}

      <FormTemplateForm
        open={formOpen}
        onOpenChange={setFormOpen}
        template={editing}
        onSaved={() => qc.invalidateQueries({ queryKey: ['admin', 'form-templates'] })}
      />
    </div>
  );
}
