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

import { useEffect, 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 { trackProductEvent } from '@/lib/analytics';
import {
  ADMIN_REPORT_TEMPLATE_CREATED,
  ADMIN_REPORT_TEMPLATE_DELETED,
  ADMIN_REPORT_TEMPLATE_UPDATED,
  ADMIN_REPORT_TEMPLATES_VIEWED,
} from '@/lib/event-catalog';
import { formatRelativeTime } from '@/lib/format';

interface ReportTemplateRow {
  id: number;
  user_id: number | null;
  user_name: string | null;
  user_email: string | null;
  name: string;
  description: string | null;
  sections: Record<string, unknown>[];
  filters: Record<string, unknown>;
  is_system: boolean;
  section_count: number;
  created_at: string;
  updated_at: string;
}

interface PaginatedTemplates {
  data: ReportTemplateRow[];
  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;
  description: string;
  sections: string; // JSON string for editing
  is_system: boolean;
};

const defaultForm: TemplateFormData = {
  name: '',
  description: '',
  sections: '[]',
  is_system: true,
};

export default function ReportTemplatesIndex({ templates, filters, stats }: Props) {
  useEffect(() => {
    trackProductEvent(ADMIN_REPORT_TEMPLATES_VIEWED, {
      total_templates: stats.total,
      system_templates: stats.system,
      user_templates: stats.user,
    });
    // intentional: fire-once on mount
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const isNavigating = useNavigationState();
  const searchRef = useRef<HTMLInputElement>(null);
  const [createOpen, setCreateOpen] = useState(false);
  const [editTemplate, setEditTemplate] = useState<ReportTemplateRow | null>(null);
  const [form, setForm] = useState<TemplateFormData>(defaultForm);
  const [formErrors, setFormErrors] = useState<Record<string, string>>({});
  const [sectionsJsonError, setSectionsJsonError] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);

  const { search, setSearch, updateFilter, handlePage } = useAdminFilters({
    route: route('admin.report-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({});
    setSectionsJsonError(null);
    setCreateOpen(true);
  }

  function openEdit(template: ReportTemplateRow) {
    setForm({
      name: template.name,
      description: template.description ?? '',
      sections: JSON.stringify(template.sections, null, 2),
      is_system: template.is_system,
    });
    setFormErrors({});
    setSectionsJsonError(null);
    setEditTemplate(template);
  }

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

  function handleSubmit() {
    let parsedSections: unknown;
    try {
      parsedSections = JSON.parse(form.sections);
    } catch {
      setSectionsJsonError('Invalid JSON. Fix before saving.');
      return;
    }

    if (!Array.isArray(parsedSections)) {
      setSectionsJsonError('Sections must be a JSON array.');
      return;
    }

    setSectionsJsonError(null);

    const payload = {
      name: form.name,
      description: form.description || null,
      sections: parsedSections,
      is_system: form.is_system,
    };

    setSubmitting(true);

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

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

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

        <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
          <PageHeader
            title="Report Templates"
            description="System and user-defined report section 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 report 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.report-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="report templates"
          emptyIcon={BarChart3}
          emptyTitle="No report templates found"
        >
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Name</TableHead>
                <TableHead>Type</TableHead>
                <TableHead>Owner</TableHead>
                <TableHead>Sections</TableHead>
                <TableHead>Description</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.section_count}</TableCell>
                  <TableCell className="max-w-48 truncate text-sm text-muted-foreground">
                    {template.description ?? '—'}
                  </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 report template?"
                        description={`"${template.name}" will be permanently deleted.`}
                        confirmLabel="Delete"
                        variant="destructive"
                        onConfirm={() => {
                          router.delete(route('admin.report-templates.destroy', template.id));
                          trackProductEvent(ADMIN_REPORT_TEMPLATE_DELETED, {
                            template_id: template.id,
                            is_system: template.is_system,
                          });
                        }}
                      />
                    </div>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </AdminDataTable>
      </div>

      <Dialog open={dialogOpen} onOpenChange={(open) => { if (!open) closeDialog(); }}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>{editTemplate ? 'Edit Report Template' : 'New Report 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-description">Description</Label>
              <Input
                id="template-description"
                value={form.description}
                onChange={(e) => setForm((f) => ({ ...f, description: e.target.value }))}
                placeholder="Optional description"
              />
              {formErrors.description && <p className="text-sm text-destructive">{formErrors.description}</p>}
            </div>
            <div className="space-y-1.5">
              <Label htmlFor="template-sections">Sections (JSON array)</Label>
              <Textarea
                id="template-sections"
                value={form.sections}
                onChange={(e) => setForm((f) => ({ ...f, sections: e.target.value }))}
                placeholder='[{"type": "summary", "title": "Executive Summary"}]'
                rows={8}
                className="font-mono text-sm"
              />
              {sectionsJsonError && <p className="text-sm text-destructive">{sectionsJsonError}</p>}
              {formErrors.sections && <p className="text-sm text-destructive">{formErrors.sections}</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>
  );
}
