'use client';

import { useState } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { type ColumnDef } from '@tanstack/react-table';
import { Pencil, Trash2, Plus } from 'lucide-react';

import { DataTable } from '@/components/shared/data-table';
import { PageHeader } from '@/components/shared/page-header';
import { ConfirmationDialog } from '@/components/shared/confirmation-dialog';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { WarningCallout } from '@/components/ui/warning-callout';
import { apiFetch } from '@/lib/api/client';
import { CustomFieldForm, type CustomFieldDefinition } from './custom-field-form';

// ─── Types ────────────────────────────────────────────────────────────────────

type EntityTab = 'client' | 'interest' | 'berth';

const TAB_LABELS: Record<EntityTab, string> = {
  client: 'Clients',
  interest: 'Interests',
  berth: 'Berths',
};

const FIELD_TYPE_LABELS: Record<string, string> = {
  text: 'Text',
  number: 'Number',
  date: 'Date',
  boolean: 'Yes / No',
  select: 'Dropdown',
};

// ─── Component ────────────────────────────────────────────────────────────────

const FIELDS_QUERY_KEY = ['admin', 'custom-fields'] as const;

export function CustomFieldsManager() {
  const queryClient = useQueryClient();
  const [activeTab, setActiveTab] = useState<EntityTab>('client');
  const [formOpen, setFormOpen] = useState(false);
  const [editingField, setEditingField] = useState<CustomFieldDefinition | null>(null);

  const { data: fields = [], isLoading: loading } = useQuery<CustomFieldDefinition[]>({
    queryKey: FIELDS_QUERY_KEY,
    queryFn: () =>
      apiFetch<{ data: CustomFieldDefinition[] }>('/api/v1/admin/custom-fields').then(
        (r) => r.data,
      ),
  });

  const fetchFields = () => queryClient.invalidateQueries({ queryKey: FIELDS_QUERY_KEY });

  const deleteMutation = useMutation({
    mutationFn: (id: string) => apiFetch(`/api/v1/admin/custom-fields/${id}`, { method: 'DELETE' }),
    onSuccess: () => fetchFields(),
  });
  const deletingId = deleteMutation.isPending ? deleteMutation.variables : null;

  const filteredFields = fields.filter((f) => f.entityType === activeTab);

  function handleCreate() {
    setEditingField(null);
    setFormOpen(true);
  }

  function handleEdit(field: CustomFieldDefinition) {
    setEditingField(field);
    setFormOpen(true);
  }

  function handleDelete(id: string) {
    deleteMutation.mutate(id);
  }

  function getDeleteDescription(field: CustomFieldDefinition): string {
    return `Are you sure you want to delete "${field.fieldLabel}" (${field.fieldName})? All stored values for this field will also be permanently deleted.`;
  }

  const columns: ColumnDef<CustomFieldDefinition, unknown>[] = [
    {
      accessorKey: 'fieldName',
      header: 'Name',
      cell: ({ row }) => <span className="font-mono text-sm">{row.original.fieldName}</span>,
    },
    {
      accessorKey: 'fieldLabel',
      header: 'Label',
      cell: ({ row }) => <span className="font-medium">{row.original.fieldLabel}</span>,
    },
    {
      accessorKey: 'fieldType',
      header: 'Type',
      cell: ({ row }) => (
        <Badge variant="secondary">
          {FIELD_TYPE_LABELS[row.original.fieldType] ?? row.original.fieldType}
        </Badge>
      ),
    },
    {
      accessorKey: 'isRequired',
      header: 'Required',
      cell: ({ row }) =>
        row.original.isRequired ? (
          <Badge variant="destructive" className="text-xs">
            Required
          </Badge>
        ) : (
          <span className="text-xs text-muted-foreground">Optional</span>
        ),
    },
    {
      accessorKey: 'sortOrder',
      header: 'Order',
      cell: ({ row }) => (
        <span className="tabular-nums text-muted-foreground">{row.original.sortOrder}</span>
      ),
    },
    {
      id: 'actions',
      header: '',
      cell: ({ row }) => (
        <div className="flex items-center justify-end gap-1">
          <Button variant="ghost" size="sm" onClick={() => handleEdit(row.original)}>
            <Pencil className="h-4 w-4" aria-hidden />
            <span className="sr-only">Edit</span>
          </Button>
          <ConfirmationDialog
            trigger={
              <Button
                variant="ghost"
                size="sm"
                className="text-destructive hover:text-destructive"
                disabled={deletingId === row.original.id}
              >
                <Trash2 className="h-4 w-4" aria-hidden />
                <span className="sr-only">Delete</span>
              </Button>
            }
            title="Delete Custom Field"
            description={getDeleteDescription(row.original)}
            confirmLabel="Delete Field"
            onConfirm={() => handleDelete(row.original.id)}
            loading={deletingId === row.original.id}
          />
        </div>
      ),
      enableSorting: false,
      size: 80,
    },
  ];

  return (
    <div className="space-y-6">
      <PageHeader
        title="Custom Fields"
        description="Define custom fields for clients and records"
        actions={
          <Button onClick={handleCreate}>
            <Plus className="mr-1.5 h-4 w-4" aria-hidden />
            New Field
          </Button>
        }
      />

      <WarningCallout title="Heads up">
        <span className="text-xs">
          Custom fields render in detail-page sidebars and the entity export, and merge-tokens of
          the form <code className="rounded bg-amber-100 px-1">{`{{custom.fieldName}}`}</code> now
          expand in EOI/contract/email templates for client/interest/berth contexts. They still
          don&rsquo;t plug into the global search index, the berth recommender, or the entity-diff
          audit log - use them for rep-only annotations and template-merge values, but anything
          load-bearing for the deal flow still needs a first-class column.
        </span>
      </WarningCallout>

      <Tabs value={activeTab} onValueChange={(v) => setActiveTab(v as EntityTab)}>
        <TabsList>
          {(Object.keys(TAB_LABELS) as EntityTab[]).map((tab) => (
            <TabsTrigger key={tab} value={tab}>
              {TAB_LABELS[tab]}
            </TabsTrigger>
          ))}
        </TabsList>

        {(Object.keys(TAB_LABELS) as EntityTab[]).map((tab) => (
          <TabsContent key={tab} value={tab} className="mt-4">
            <DataTable
              columns={columns}
              data={filteredFields}
              isLoading={loading}
              getRowId={(row) => row.id}
              cardRender={({ original }) => (
                <div className="rounded-xl border border-border bg-card p-4 shadow-sm">
                  <div className="flex items-start justify-between gap-3">
                    <div className="min-w-0 flex-1">
                      <p className="truncate text-sm font-semibold text-foreground">
                        {original.fieldLabel}
                      </p>
                      <p className="mt-0.5 truncate font-mono text-xs text-muted-foreground">
                        {original.fieldName}
                      </p>
                      <div className="mt-2 flex flex-wrap items-center gap-1.5 text-xs">
                        <Badge variant="secondary">
                          {FIELD_TYPE_LABELS[original.fieldType] ?? original.fieldType}
                        </Badge>
                        {original.isRequired ? (
                          <Badge variant="destructive" className="text-xs">
                            Required
                          </Badge>
                        ) : (
                          <span className="text-muted-foreground">Optional</span>
                        )}
                        <span aria-hidden className="text-muted-foreground">
                          ·
                        </span>
                        <span className="tabular-nums text-muted-foreground">
                          Order {original.sortOrder}
                        </span>
                      </div>
                    </div>
                    <div className="flex shrink-0 items-center gap-1">
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleEdit(original)}
                        aria-label="Edit field"
                      >
                        <Pencil className="h-4 w-4" aria-hidden />
                      </Button>
                      <ConfirmationDialog
                        trigger={
                          <Button
                            variant="ghost"
                            size="sm"
                            className="text-destructive hover:text-destructive"
                            disabled={deletingId === original.id}
                            aria-label="Delete field"
                          >
                            <Trash2 className="h-4 w-4" aria-hidden />
                          </Button>
                        }
                        title="Delete Custom Field"
                        description={getDeleteDescription(original)}
                        confirmLabel="Delete Field"
                        onConfirm={() => handleDelete(original.id)}
                        loading={deletingId === original.id}
                      />
                    </div>
                  </div>
                </div>
              )}
              emptyState={
                <div className="py-8 text-center">
                  <p className="text-muted-foreground">
                    No custom fields for {TAB_LABELS[tab]} yet.
                  </p>
                  <Button variant="link" onClick={handleCreate} className="mt-2">
                    Create the first field
                  </Button>
                </div>
              }
            />
          </TabsContent>
        ))}
      </Tabs>

      <CustomFieldForm
        open={formOpen}
        onOpenChange={setFormOpen}
        field={editingField}
        onSuccess={fetchFields}
      />
    </div>
  );
}
