'use client';

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

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 { StatusPill } from '@/components/ui/status-pill';
import { Sheet, SheetContent, SheetHeader, SheetTitle } from '@/components/ui/sheet';
import { apiFetch } from '@/lib/api/client';
import { TemplateForm } from './template-form';
import { TemplateVersionHistory } from './template-version-history';
import { TemplatePreview } from './template-preview';

interface AdminTemplate {
  id: string;
  name: string;
  templateType: string;
  bodyHtml: string;
  version: number;
  isActive: boolean;
  createdAt: string;
  updatedAt: string;
  content: Record<string, unknown> | null;
}

const TYPE_LABELS: Record<string, string> = {
  eoi: 'EOI',
  contract: 'Contract',
  nda: 'NDA',
  reservation_agreement: 'Reservation Agreement',
  letter: 'Letter',
  other: 'Other',
  welcome_letter: 'Welcome Letter',
  handover_checklist: 'Handover Checklist',
  acknowledgment: 'Acknowledgment',
  correspondence: 'Correspondence',
  custom: 'Custom',
};

const TEMPLATES_QUERY_KEY = ['admin', 'document-templates'] as const;

export function TemplateList() {
  const queryClient = useQueryClient();
  const [formOpen, setFormOpen] = useState(false);
  const [editingTemplate, setEditingTemplate] = useState<AdminTemplate | null>(null);
  const [historyTemplate, setHistoryTemplate] = useState<AdminTemplate | null>(null);
  const [historyOpen, setHistoryOpen] = useState(false);

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

  const fetchTemplates = () => queryClient.invalidateQueries({ queryKey: TEMPLATES_QUERY_KEY });

  function handleNewTemplate() {
    setEditingTemplate(null);
    setFormOpen(true);
  }

  function handleEditTemplate(template: AdminTemplate) {
    setEditingTemplate(template);
    setFormOpen(true);
  }

  function handleViewHistory(template: AdminTemplate) {
    setHistoryTemplate(template);
    setHistoryOpen(true);
  }

  async function handleDeleteTemplate(id: string) {
    await apiFetch(`/api/v1/admin/templates/${id}`, { method: 'DELETE' });
    await fetchTemplates();
  }

  async function handleToggleActive(template: AdminTemplate) {
    await apiFetch(`/api/v1/admin/templates/${template.id}`, {
      method: 'PATCH',
      body: { isActive: !template.isActive },
    });
    await fetchTemplates();
  }

  const columns: ColumnDef<AdminTemplate, unknown>[] = [
    {
      accessorKey: 'name',
      header: 'Name',
      cell: ({ row }) => (
        <div className="flex items-center gap-2">
          <FileText className="h-4 w-4 shrink-0 text-muted-foreground" aria-hidden />
          <span className="font-medium">{row.original.name}</span>
        </div>
      ),
    },
    {
      accessorKey: 'templateType',
      header: 'Type',
      cell: ({ row }) => (
        <Badge variant="secondary">
          {TYPE_LABELS[row.original.templateType] ?? row.original.templateType}
        </Badge>
      ),
    },
    {
      accessorKey: 'version',
      header: 'Version',
      cell: ({ row }) => (
        <span className="text-sm text-muted-foreground">v{row.original.version}</span>
      ),
    },
    {
      accessorKey: 'isActive',
      header: 'Status',
      cell: ({ row }) =>
        row.original.isActive ? (
          <StatusPill status="enabled">Active</StatusPill>
        ) : (
          <StatusPill status="disabled">Inactive</StatusPill>
        ),
    },
    {
      accessorKey: 'updatedAt',
      header: 'Last Updated',
      cell: ({ row }) =>
        new Date(row.original.updatedAt).toLocaleDateString(undefined, {
          day: '2-digit',
          month: 'short',
          year: 'numeric',
        }),
    },
    {
      id: 'actions',
      header: '',
      cell: ({ row }) => (
        <div className="flex items-center justify-end gap-1">
          <TemplatePreview content={row.original.content} templateName={row.original.name} />
          <Button
            variant="ghost"
            size="icon"
            title="Version history"
            onClick={() => handleViewHistory(row.original)}
          >
            <History className="h-4 w-4" aria-hidden />
          </Button>
          <Button
            variant="ghost"
            size="icon"
            title="Edit template"
            onClick={() => handleEditTemplate(row.original)}
          >
            <Pencil className="h-4 w-4" aria-hidden />
          </Button>
          <Button
            variant="ghost"
            size="icon"
            title={row.original.isActive ? 'Deactivate' : 'Activate'}
            onClick={() => handleToggleActive(row.original)}
          >
            <span className="text-xs">{row.original.isActive ? 'Off' : 'On'}</span>
          </Button>
          <ConfirmationDialog
            trigger={
              <Button variant="ghost" size="icon" title="Delete template">
                <Trash2 className="h-4 w-4 text-destructive" aria-hidden />
              </Button>
            }
            title="Delete Template"
            description={`Are you sure you want to delete "${row.original.name}"? This action cannot be undone.`}
            confirmLabel="Delete"
            destructive
            onConfirm={() => handleDeleteTemplate(row.original.id)}
          />
        </div>
      ),
    },
  ];

  return (
    <div className="space-y-6">
      <PageHeader
        title="Document Templates"
        description="Manage reusable document templates with TipTap content and PDF generation"
        actions={
          <Button onClick={handleNewTemplate}>
            <Plus className="mr-2 h-4 w-4" aria-hidden />
            New Template
          </Button>
        }
      />

      <DataTable
        columns={columns}
        data={templates}
        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">
                <div className="flex items-center gap-2">
                  <FileText className="h-4 w-4 shrink-0 text-muted-foreground" aria-hidden />
                  <p className="truncate text-sm font-semibold text-foreground">{original.name}</p>
                </div>
                <div className="mt-1 flex flex-wrap items-center gap-1.5 text-xs text-muted-foreground">
                  <Badge variant="secondary">
                    {TYPE_LABELS[original.templateType] ?? original.templateType}
                  </Badge>
                  <span>v{original.version}</span>
                  {original.isActive ? (
                    <StatusPill status="enabled">Active</StatusPill>
                  ) : (
                    <StatusPill status="disabled">Inactive</StatusPill>
                  )}
                  <span aria-hidden>·</span>
                  <span>
                    Updated{' '}
                    {new Date(original.updatedAt).toLocaleDateString(undefined, {
                      day: '2-digit',
                      month: 'short',
                      year: 'numeric',
                    })}
                  </span>
                </div>
              </div>
              <div className="flex shrink-0 items-center gap-0.5">
                <TemplatePreview content={original.content} templateName={original.name} />
                <Button
                  variant="ghost"
                  size="icon"
                  title="Version history"
                  onClick={() => handleViewHistory(original)}
                >
                  <History className="h-4 w-4" aria-hidden />
                </Button>
                <Button
                  variant="ghost"
                  size="icon"
                  title="Edit template"
                  onClick={() => handleEditTemplate(original)}
                >
                  <Pencil className="h-4 w-4" aria-hidden />
                </Button>
                <ConfirmationDialog
                  trigger={
                    <Button variant="ghost" size="icon" title="Delete template">
                      <Trash2 className="h-4 w-4 text-destructive" aria-hidden />
                    </Button>
                  }
                  title="Delete Template"
                  description={`Are you sure you want to delete "${original.name}"? This action cannot be undone.`}
                  confirmLabel="Delete"
                  destructive
                  onConfirm={() => handleDeleteTemplate(original.id)}
                />
              </div>
            </div>
          </div>
        )}
        emptyState={
          <div className="py-10 text-center text-muted-foreground">
            No document templates yet. Create your first template to get started.
          </div>
        }
      />

      <TemplateForm
        open={formOpen}
        onOpenChange={setFormOpen}
        template={editingTemplate}
        onSuccess={fetchTemplates}
      />

      {/* Version History Sheet */}
      <Sheet open={historyOpen} onOpenChange={setHistoryOpen}>
        <SheetContent className="w-full max-w-xl sm:max-w-xl overflow-y-auto">
          <SheetHeader>
            <SheetTitle>Version History - {historyTemplate?.name}</SheetTitle>
          </SheetHeader>
          <div className="mt-6">
            {historyTemplate && (
              <TemplateVersionHistory
                templateId={historyTemplate.id}
                currentVersion={historyTemplate.version}
                onRollback={() => {
                  void fetchTemplates();
                  setHistoryOpen(false);
                }}
              />
            )}
          </div>
        </SheetContent>
      </Sheet>
    </div>
  );
}
