import { Bot, Pencil, PlusCircle, Search, Trash2 } from 'lucide-react';

import { useRef, useState } from 'react';

import { Head, Link, router } from '@inertiajs/react';

import { AdminDataTable } from '@/Components/admin/AdminDataTable';
import { AdminStatsGrid, type StatCard } from '@/Components/admin/AdminStatsGrid';
import PageHeader from '@/Components/layout/PageHeader';
import { Badge } from '@/Components/ui/badge';
import {
  Breadcrumb,
  BreadcrumbItem,
  BreadcrumbLink,
  BreadcrumbList,
  BreadcrumbPage,
  BreadcrumbSeparator,
} from '@/Components/ui/breadcrumb';
import { Button } from '@/Components/ui/button';
import { Checkbox } from '@/Components/ui/checkbox';
import { ConfirmDialog } from '@/Components/ui/confirm-dialog';
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/Components/ui/dialog';
import { ExportButton } from '@/Components/ui/export-button';
import { Input } from '@/Components/ui/input';
import { Label } from '@/Components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/Components/ui/select';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/Components/ui/table';
import { Textarea } from '@/Components/ui/textarea';
import { useAdminFilters } from '@/hooks/useAdminFilters';
import { useAdminKeyboardShortcuts } from '@/hooks/useAdminKeyboardShortcuts';
import { useNavigationState } from '@/hooks/useNavigationState';
import AdminLayout from '@/Layouts/AdminLayout';
import { formatRelativeTime } from '@/lib/format';

interface AiTemplateRow {
  id: number;
  user_id: number | null;
  user_name: string | null;
  user_email: string | null;
  name: string;
  content: string;
  variables: string[];
  is_system: boolean;
  variable_count: number;
  created_at: string;
  updated_at: string;
}

interface PaginatedTemplates {
  data: AiTemplateRow[];
  current_page: number;
  last_page: number;
  from: number | null;
  to: number | null;
  total: number;
}

interface Stats {
  total: number;
  system: number;
  user: number;
}

interface Props {
  templates: PaginatedTemplates;
  filters: { search: string; system_only: boolean; user_only: boolean };
  stats: Stats;
}

type TemplateFormData = {
  name: string;
  content: string;
  variables: string; // comma-separated for editing
  is_system: boolean;
};

const defaultForm: TemplateFormData = {
  name: '',
  content: '',
  variables: '',
  is_system: true,
};

export default function AiTemplatesIndex({ templates, filters, stats }: Props) {
  const isNavigating = useNavigationState();
  const searchRef = useRef<HTMLInputElement>(null);
  const [createOpen, setCreateOpen] = useState(false);
  const [editTemplate, setEditTemplate] = useState<AiTemplateRow | null>(null);
  const [form, setForm] = useState<TemplateFormData>(defaultForm);
  const [formErrors, setFormErrors] = useState<Record<string, string>>({});
  const [submitting, setSubmitting] = useState(false);

  const { search, setSearch, updateFilter, handlePage } = useAdminFilters({
    route: route('admin.ai-templates.index'),
    filters,
  });

  const typeFilter = filters.system_only ? 'system' : filters.user_only ? 'user' : 'all';

  const exportParams: Record<string, string> = {};
  if (filters.search) exportParams.search = filters.search;
  if (filters.system_only) exportParams.system_only = '1';
  if (filters.user_only) exportParams.user_only = '1';

  useAdminKeyboardShortcuts({
    onSearch: () => searchRef.current?.focus(),
    onNextPage: templates.current_page < templates.last_page ? () => handlePage(templates.current_page + 1) : undefined,
    onPrevPage: templates.current_page > 1 ? () => handlePage(templates.current_page - 1) : undefined,
  });

  const statCards: StatCard[] = [
    { title: 'Total', value: stats.total },
    { title: 'System', value: stats.system },
    { title: 'User', value: stats.user },
  ];

  function openCreate() {
    setForm(defaultForm);
    setFormErrors({});
    setCreateOpen(true);
  }

  function openEdit(template: AiTemplateRow) {
    setForm({
      name: template.name,
      content: template.content,
      variables: template.variables.join(', '),
      is_system: template.is_system,
    });
    setFormErrors({});
    setEditTemplate(template);
  }

  function closeDialog() {
    setCreateOpen(false);
    setEditTemplate(null);
    setFormErrors({});
  }

  function handleSubmit() {
    const payload = {
      name: form.name,
      content: form.content,
      variables: form.variables
        .split(',')
        .map((v) => v.trim())
        .filter(Boolean),
      is_system: form.is_system,
    };

    setSubmitting(true);

    if (editTemplate) {
      router.put(route('admin.ai-templates.update', editTemplate.id), payload, {
        onSuccess: () => { setSubmitting(false); closeDialog(); },
        onError: (errs) => { setSubmitting(false); setFormErrors(errs); },
      });
    } else {
      router.post(route('admin.ai-templates.store'), payload, {
        onSuccess: () => { setSubmitting(false); closeDialog(); },
        onError: (errs) => { setSubmitting(false); setFormErrors(errs); },
      });
    }
  }

  const dialogOpen = createOpen || editTemplate !== null;

  return (
    <AdminLayout>
      <Head title="AI Templates" />
      <div className="container py-6 space-y-6">
        <Breadcrumb>
          <BreadcrumbList>
            <BreadcrumbItem>
              <BreadcrumbLink asChild>
                <Link href="/admin">Admin</Link>
              </BreadcrumbLink>
            </BreadcrumbItem>
            <BreadcrumbSeparator />
            <BreadcrumbItem>
              <BreadcrumbPage>AI Templates</BreadcrumbPage>
            </BreadcrumbItem>
          </BreadcrumbList>
        </Breadcrumb>

        <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
          <PageHeader
            title="AI Templates"
            description="System and user-defined AI prompt templates."
          />
          <div className="flex flex-wrap items-center gap-2">
            <div className="relative">
              <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
              <Input
                ref={searchRef}
                placeholder="Search templates…"
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                className="pl-9 w-52"
                aria-label="Search AI templates"
              />
            </div>
            <Select
              value={typeFilter}
              onValueChange={(value) =>
                updateFilter({
                  system_only: value === 'system',
                  user_only: value === 'user',
                })
              }
            >
              <SelectTrigger className="w-36">
                <SelectValue placeholder="All types" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All types</SelectItem>
                <SelectItem value="system">System only</SelectItem>
                <SelectItem value="user">User only</SelectItem>
              </SelectContent>
            </Select>
            <ExportButton href={route('admin.ai-templates.export')} params={exportParams} />
            <Button size="sm" onClick={openCreate}>
              <PlusCircle className="mr-2 h-4 w-4" />
              New Template
            </Button>
          </div>
        </div>

        <AdminStatsGrid stats={statCards} />

        <AdminDataTable
          isEmpty={templates.data.length === 0}
          isNavigating={isNavigating}
          pagination={templates}
          onPage={handlePage}
          paginationLabel="AI templates"
          emptyIcon={Bot}
          emptyTitle="No AI templates found"
        >
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Name</TableHead>
                <TableHead>Type</TableHead>
                <TableHead>Owner</TableHead>
                <TableHead>Variables</TableHead>
                <TableHead>Created</TableHead>
                <TableHead className="w-[120px]">Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {templates.data.map((template) => (
                <TableRow key={template.id}>
                  <TableCell className="font-medium">{template.name}</TableCell>
                  <TableCell>
                    <Badge variant={template.is_system ? 'default' : 'secondary'}>
                      {template.is_system ? 'System' : 'User'}
                    </Badge>
                  </TableCell>
                  <TableCell>
                    {template.user_name ? (
                      <div className="text-sm">
                        <div>{template.user_name}</div>
                        <div className="text-muted-foreground">{template.user_email}</div>
                      </div>
                    ) : (
                      <span className="text-muted-foreground text-sm">—</span>
                    )}
                  </TableCell>
                  <TableCell className="text-sm text-muted-foreground">{template.variable_count}</TableCell>
                  <TableCell className="text-sm text-muted-foreground">
                    {formatRelativeTime(template.created_at)}
                  </TableCell>
                  <TableCell>
                    <div className="flex items-center gap-1">
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => openEdit(template)}
                        aria-label={`Edit "${template.name}"`}
                      >
                        <Pencil className="h-3.5 w-3.5" />
                      </Button>
                      <ConfirmDialog
                        trigger={
                          <Button
                            variant="ghost"
                            size="sm"
                            className="text-destructive hover:text-destructive"
                            aria-label={`Delete "${template.name}"`}
                          >
                            <Trash2 className="h-3.5 w-3.5" />
                          </Button>
                        }
                        title="Delete AI template?"
                        description={`"${template.name}" will be permanently deleted.`}
                        confirmLabel="Delete"
                        variant="destructive"
                        onConfirm={() => router.delete(route('admin.ai-templates.destroy', template.id))}
                      />
                    </div>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </AdminDataTable>
      </div>

      <Dialog open={dialogOpen} onOpenChange={(open) => { if (!open) closeDialog(); }}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>{editTemplate ? 'Edit AI Template' : 'New AI Template'}</DialogTitle>
          </DialogHeader>
          <div className="space-y-4 py-2">
            <div className="space-y-1.5">
              <Label htmlFor="template-name">Name</Label>
              <Input
                id="template-name"
                value={form.name}
                onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
                placeholder="Template name"
              />
              {formErrors.name && <p className="text-sm text-destructive">{formErrors.name}</p>}
            </div>
            <div className="space-y-1.5">
              <Label htmlFor="template-content">Content</Label>
              <Textarea
                id="template-content"
                value={form.content}
                onChange={(e) => setForm((f) => ({ ...f, content: e.target.value }))}
                placeholder="Template content with {{variable}} placeholders…"
                rows={8}
                className="font-mono text-sm"
              />
              {formErrors.content && <p className="text-sm text-destructive">{formErrors.content}</p>}
            </div>
            <div className="space-y-1.5">
              <Label htmlFor="template-variables">Variables (comma-separated)</Label>
              <Input
                id="template-variables"
                value={form.variables}
                onChange={(e) => setForm((f) => ({ ...f, variables: e.target.value }))}
                placeholder="variable1, variable2, variable3"
              />
              {formErrors.variables && <p className="text-sm text-destructive">{formErrors.variables}</p>}
            </div>
            <div className="flex items-center gap-2">
              <Checkbox
                id="template-is-system"
                checked={form.is_system}
                onCheckedChange={(checked) =>
                  setForm((f) => ({ ...f, is_system: checked === true }))
                }
              />
              <Label htmlFor="template-is-system">System template (available to all users)</Label>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={closeDialog} disabled={submitting}>
              Cancel
            </Button>
            <Button onClick={handleSubmit} disabled={submitting}>
              {submitting ? 'Saving…' : editTemplate ? 'Save Changes' : 'Create Template'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </AdminLayout>
  );
}
