"use client";

import { useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import {
  Loader2, Plus, Edit, Trash2,
  BookOpen, FileText, HelpCircle, Star, Settings, Home,
  Car, Wrench, Shield, Bell, User, Map, Phone, Mail,
  CreditCard, Clock, CheckCircle, AlertCircle, Info,
  Zap, Globe, Lock, Eye, Heart, Search, Calendar,
} from "lucide-react";
import * as LucideIcons from "lucide-react";
import { useRepositories } from "@/di/repository-provider";
import { useT } from "@/shared/i18n/client";
import { useApiQuery } from "@/presentation/hooks/use-api-query";
import { useCrudMutations } from "@/presentation/hooks/use-crud-mutations";
import { useDeleteTarget } from "@/presentation/hooks/use-delete-target";
import { useServerPagination } from "@/presentation/hooks/use-server-pagination";
import ServerDataTable, { type Column } from "@/presentation/components/shared/server-data-table";
import ConfirmationDialog from "@/presentation/components/shared/confirmation-dialog";
import { PageNumbers } from "@/app/(dashboard)/help-center/components/page-numbers";
import { Button } from "@/presentation/components/ui/button";
import { Input } from "@/presentation/components/ui/input";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/presentation/components/ui/dialog";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/presentation/components/ui/form";
import { createHelpSectionSchema, type CreateHelpSectionFormValues } from "@/shared/schemas/help-section.schema";
import type { HelpSection } from "@/domain/entities/help-section";

// Icônes disponibles avec leur nom Lucide
const AVAILABLE_ICONS = [
  { name: "BookOpen", icon: BookOpen },
  { name: "FileText", icon: FileText },
  { name: "HelpCircle", icon: HelpCircle },
  { name: "Star", icon: Star },
  { name: "Settings", icon: Settings },
  { name: "Home", icon: Home },
  { name: "Car", icon: Car },
  { name: "Wrench", icon: Wrench },
  { name: "Shield", icon: Shield },
  { name: "Bell", icon: Bell },
  { name: "User", icon: User },
  { name: "Map", icon: Map },
  { name: "Phone", icon: Phone },
  { name: "Mail", icon: Mail },
  { name: "CreditCard", icon: CreditCard },
  { name: "Clock", icon: Clock },
  { name: "CheckCircle", icon: CheckCircle },
  { name: "AlertCircle", icon: AlertCircle },
  { name: "Info", icon: Info },
  { name: "Zap", icon: Zap },
  { name: "Globe", icon: Globe },
  { name: "Lock", icon: Lock },
  { name: "Eye", icon: Eye },
  { name: "Heart", icon: Heart },
  { name: "Search", icon: Search },
  { name: "Calendar", icon: Calendar },
];

function SectionIcon({ name, className }: { name?: string; className?: string }) {
  if (!name) return null;
  const match = AVAILABLE_ICONS.find((i) => i.name === name);
  if (!match) return null;
  const IconComp = match.icon;
  return <IconComp className={className ?? "w-4 h-4"} />;
}

export function SectionsTab() {
  const t = useT();
  const container = useRepositories();
  const pagination = useServerPagination({ perPage: 10, orderBy: "order", order: "ASC" });
  const [dialogOpen, setDialogOpen] = useState(false);
  const [editingSection, setEditingSection] = useState<HelpSection | null>(null);
  const deleteDialog = useDeleteTarget<HelpSection>();

  const { data: response, loading, refetch } = useApiQuery(
    () => container.helpSectionRepository.findAll(pagination.params),
    { deps: [pagination.params] }
  );

  const { create: createMutation, update: updateMutation, delete: deleteMutation } = useCrudMutations(
    container.helpSectionRepository,
    {
      create: { successMessage: "Section créée avec succès", onSuccess: () => { setDialogOpen(false); refetch(); } },
      update: { successMessage: "Section mise à jour avec succès", onSuccess: () => { setDialogOpen(false); setEditingSection(null); refetch(); } },
      delete: { successMessage: "Section supprimée avec succès", onSuccess: () => { deleteDialog.close(); refetch(); } },
    }
  );

  const isEditing = !!editingSection;
  const schema = createHelpSectionSchema(t);
  const form = useForm<CreateHelpSectionFormValues>({
    resolver: zodResolver(schema) as any,
    defaultValues: { name: "", description: "", icon: "", order: 0 },
  });

  const openCreate = () => {
    const sections = response?.data ?? [];
    const maxOrder = sections.length > 0
      ? Math.max(...sections.map((s) => s.order ?? 0)) + 1
      : 0;
    setEditingSection(null);
    form.reset({ name: "", description: "", icon: "", order: maxOrder });
    setDialogOpen(true);
  };

  const openEdit = (section: HelpSection) => {
    setEditingSection(section);
    form.reset({
      name: section.name,
      description: section.description || "",
      icon: section.icon || "",
      order: section.order ?? 0,
    });
    setDialogOpen(true);
  };

  const onSubmit = async (values: CreateHelpSectionFormValues) => {
    if (isEditing && editingSection) {
      await updateMutation.mutate({ id: Number(editingSection.id), data: values });
    } else {
      await createMutation.mutate(values);
    }
  };

  const sections = [...(response?.data ?? [])].sort((a, b) => (a.order ?? 0) - (b.order ?? 0));

  const columns: Column<HelpSection>[] = [
    {
      key: "order",
      label: "Ordre",
      className: "w-16 text-center",
      sortable: true,
      render: (row) => (
        <span className="text-sm text-muted-foreground">{row.order ?? 0}</span>
      ),
    },
    {
      key: "icon",
      label: "Icône",
      className: "w-16 text-center",
      render: (row) => (
        <div className="flex justify-center">
          {row.icon
            ? <SectionIcon name={row.icon} className="w-5 h-5 text-blue-600" />
            : <span className="text-muted-foreground text-xs">—</span>
          }
        </div>
      ),
    },
    { key: "name", label: "Nom", sortable: true },
    { key: "description", label: "Description", render: (row) => row.description || "—" },
    {
      key: "actions",
      label: "",
      className: "w-24 text-right",
      render: (row) => (
        <div className="flex items-center justify-end gap-2">
          <Button variant="ghost" size="icon" onClick={(e) => { e.stopPropagation(); openEdit(row); }}>
            <Edit className="w-4 h-4 text-blue-600" />
          </Button>
          <Button variant="ghost" size="icon" onClick={(e) => { e.stopPropagation(); deleteDialog.open(row); }}>
            <Trash2 className="w-4 h-4 text-red-600" />
          </Button>
        </div>
      ),
    },
  ];

  return (
    <div className="space-y-4">
      <div className="flex justify-between items-center">
        <h3 className="text-lg font-semibold">Sections</h3>
        <Button onClick={openCreate} size="sm" className="bg-blue-600 hover:bg-blue-700 text-white">
          <Plus className="w-4 h-4 mr-2" />
          Nouvelle Section
        </Button>
      </div>

      <ServerDataTable
        columns={columns}
        data={sections}
        total={response?.meta?.total ?? sections.length}
        page={pagination.page}
        totalPages={1}
        loading={loading}
        search={pagination.search}
        onSearchChange={pagination.setSearch}
        onPageChange={pagination.setPage}
        onSortChange={pagination.setSort}
        sortBy={pagination.orderBy}
        sortOrder={pagination.order}
        emptyMessage="Aucune section trouvée"
      />

      {(response?.meta?.last_page ?? 1) > 1 && (
        <div className="flex justify-end">
          <PageNumbers
            page={pagination.page}
            totalPages={response?.meta?.last_page ?? 1}
            onPageChange={pagination.setPage}
          />
        </div>
      )}

      <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
        <DialogContent className="max-w-lg">
          <DialogHeader>
            <DialogTitle>{isEditing ? "Modifier la section" : "Nouvelle section"}</DialogTitle>
          </DialogHeader>
          <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
              <FormField
                control={form.control}
                name="name"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Nom</FormLabel>
                    <FormControl>
                      <Input placeholder="Nom de la section" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="description"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Description</FormLabel>
                    <FormControl>
                      <Input placeholder="Description" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="order"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Ordre d'affichage</FormLabel>
                    <FormControl>
                      <Input type="number" min={0} placeholder="0" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="icon"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Icône</FormLabel>
                    <div className="grid grid-cols-9 gap-1.5 p-3 border border-border rounded-md bg-muted/30">
                      {AVAILABLE_ICONS.map(({ name, icon: IconComp }) => (
                        <button
                          key={name}
                          type="button"
                          title={name}
                          onClick={() => field.onChange(field.value === name ? "" : name)}
                          className={[
                            "flex items-center justify-center w-8 h-8 rounded-md transition-colors",
                            field.value === name
                              ? "bg-blue-600 text-white"
                              : "hover:bg-muted text-muted-foreground hover:text-foreground",
                          ].join(" ")}
                        >
                          <IconComp className="w-4 h-4" />
                        </button>
                      ))}
                    </div>
                    {field.value && (
                      <p className="text-xs text-muted-foreground mt-1">
                        Icône sélectionnée : <span className="font-medium text-foreground">{field.value}</span>
                      </p>
                    )}
                    <FormMessage />
                  </FormItem>
                )}
              />
              <div className="flex justify-end pt-2">
                <Button type="submit" disabled={createMutation.loading || updateMutation.loading}>
                  {(createMutation.loading || updateMutation.loading) && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
                  {isEditing ? "Enregistrer" : "Créer"}
                </Button>
              </div>
            </form>
          </Form>
        </DialogContent>
      </Dialog>

      <ConfirmationDialog
        open={deleteDialog.isOpen}
        onOpenChange={(open) => { if (!open) deleteDialog.close(); }}
        title="Supprimer la section"
        description={`Êtes-vous sûr de vouloir supprimer la section "${deleteDialog.target?.name}" ? Cette action est irréversible.`}
        confirmLabel="Supprimer"
        cancelLabel="Annuler"
        onConfirm={() => deleteDialog.target && deleteMutation.mutate(Number(deleteDialog.target.id))}
        loading={deleteMutation.loading}
        variant="destructive"
      />
    </div>
  );
}
