'use client';

import { useState, useCallback, useEffect } from 'react';
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 { 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 ────────────────────────────────────────────────────────────────

export function CustomFieldsManager() {
  const [activeTab, setActiveTab] = useState<EntityTab>('client');
  const [fields, setFields] = useState<CustomFieldDefinition[]>([]);
  const [loading, setLoading] = useState(true);
  const [formOpen, setFormOpen] = useState(false);
  const [editingField, setEditingField] = useState<CustomFieldDefinition | null>(null);
  const [deletingId, setDeletingId] = useState<string | null>(null);

  const fetchFields = useCallback(async () => {
    setLoading(true);
    try {
      const res = await apiFetch<{ data: CustomFieldDefinition[] }>(
        '/api/v1/admin/custom-fields',
      );
      setFields(res.data);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    void fetchFields();
  }, [fetchFields]);

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

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

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

  async function handleDelete(id: string) {
    setDeletingId(id);
    try {
      await apiFetch(`/api/v1/admin/custom-fields/${id}`, { method: 'DELETE' });
      await fetchFields();
    } finally {
      setDeletingId(null);
    }
  }

  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" />
            <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" />
                <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" />
            New Field
          </Button>
        }
      />

      <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}
              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>
  );
}
