"use client";

import { useMemo, useState } from "react";
import {
  Mail,
  Clock,
  ChevronDown,
  Loader2,
  Users,
  Search,
  Plus,
  MoreVertical,
  Pencil,
  Trash2,
  KeyRound,
  Archive,
  ArchiveRestore,
} from "lucide-react";
import { useRepositories } from "@/di/repository-provider";
import { useApiQuery } from "@/presentation/hooks/use-api-query";
import { useApiMutation } from "@/presentation/hooks/use-api-mutation";
import { usePageHeader } from "@/presentation/hooks/use-page-header";
import { useT, useLocale } from "@/shared/i18n/client";
import { formatDate } from "@/shared/lib/format-date";
import { Badge } from "@/presentation/components/ui/badge";
import { Button } from "@/presentation/components/ui/button";
import { Input } from "@/presentation/components/ui/input";
import { Avatar, AvatarFallback } from "@/presentation/components/ui/avatar";
import {
  Tabs,
  TabsList,
  TabsTrigger,
  TabsContent,
} from "@/presentation/components/ui/tabs";
import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from "@/presentation/components/ui/collapsible";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/presentation/components/ui/dropdown-menu";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/presentation/components/ui/alert-dialog";
import { InstallerFormDialog } from "@/presentation/components/installers/installer-form-dialog";
import { InstallerPasswordDialog } from "@/presentation/components/installers/installer-password-dialog";
import type { Installer } from "@/domain/entities/installer";
import type { Locale } from "@/shared/i18n/config";

type Tab = "active" | "archived";

function initials(name: string): string {
  return (
    name
      .split(" ")
      .map((w) => w[0])
      .join("")
      .slice(0, 2)
      .toUpperCase() || "?"
  );
}

function StatTile({
  value,
  label,
  tone = "default",
}: {
  value: string | number;
  label: string;
  tone?: "default" | "green" | "blue";
}) {
  const toneClass =
    tone === "green"
      ? "bg-emerald-50 text-emerald-700"
      : tone === "blue"
        ? "bg-blue-50 text-blue-700"
        : "bg-muted/50 text-foreground";
  return (
    <div className={`rounded-lg px-3 py-2.5 text-center ${toneClass}`}>
      <div className="text-xl font-bold leading-none">{value}</div>
      <div className="text-[11px] font-medium opacity-80 mt-1">{label}</div>
    </div>
  );
}

function InstallerCard({
  installer,
  locale,
  archived,
  onEdit,
  onChangePassword,
  onArchive,
  onRestore,
  onForceDelete,
}: {
  installer: Installer;
  locale: Locale;
  archived: boolean;
  onEdit: (installer: Installer) => void;
  onChangePassword: (installer: Installer) => void;
  onArchive: (installer: Installer) => void;
  onRestore: (installer: Installer) => void;
  onForceDelete: (installer: Installer) => void;
}) {
  const t = useT();
  const i = t.installers;
  const { total, validated, errors, ok_rate, avg_minutes } = installer.stats;
  const validatedPct = total > 0 ? (validated / total) * 100 : 0;
  const errorsPct = total > 0 ? (errors / total) * 100 : 0;

  return (
    <div className="bg-card rounded-xl border border-border shadow-sm p-4 space-y-4">
      {/* Header */}
      <div className="flex items-center gap-3">
        <Avatar className="w-10 h-10 flex-shrink-0">
          <AvatarFallback className="bg-blue-50 text-blue-600 text-sm font-bold">
            {initials(installer.name)}
          </AvatarFallback>
        </Avatar>
        <div className="min-w-0 flex-1">
          <div className="flex items-center gap-2 flex-wrap">
            <span className="text-sm font-bold text-foreground truncate">
              {installer.name}
            </span>
            <Badge
              variant={archived ? "outline" : "secondary"}
              className="text-[10px] px-1.5 py-0"
            >
              {archived ? i.archivedBadge : i.badge}
            </Badge>
          </div>
        </div>
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="ghost" size="icon" className="h-8 w-8 shrink-0">
              <MoreVertical className="w-4 h-4" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            {archived ? (
              <>
                <DropdownMenuItem onClick={() => onRestore(installer)}>
                  <ArchiveRestore className="w-4 h-4 mr-2" />
                  {i.manage.restore}
                </DropdownMenuItem>
                <DropdownMenuItem
                  variant="destructive"
                  onClick={() => onForceDelete(installer)}
                >
                  <Trash2 className="w-4 h-4 mr-2" />
                  {i.manage.deleteForever}
                </DropdownMenuItem>
              </>
            ) : (
              <>
                <DropdownMenuItem onClick={() => onEdit(installer)}>
                  <Pencil className="w-4 h-4 mr-2" />
                  {i.manage.edit}
                </DropdownMenuItem>
                <DropdownMenuItem onClick={() => onChangePassword(installer)}>
                  <KeyRound className="w-4 h-4 mr-2" />
                  {i.manage.changePassword}
                </DropdownMenuItem>
                <DropdownMenuItem
                  variant="destructive"
                  onClick={() => onArchive(installer)}
                >
                  <Archive className="w-4 h-4 mr-2" />
                  {i.manage.archive}
                </DropdownMenuItem>
              </>
            )}
          </DropdownMenuContent>
        </DropdownMenu>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-3 gap-2">
        <StatTile value={total} label={i.stats.installations} />
        <StatTile value={`${ok_rate}%`} label={i.stats.okRate} tone="green" />
        <StatTile
          value={avg_minutes ?? "—"}
          label={i.stats.avgMin}
          tone="blue"
        />
      </div>

      {/* Validées / erreurs bar */}
      <div>
        <div className="flex items-center justify-between text-xs mb-1">
          <span className="text-emerald-600 font-medium">
            {i.validatedCount(validated)}
          </span>
          <span className="text-red-500 font-medium">{i.errorsCount(errors)}</span>
        </div>
        <div className="flex h-2 w-full overflow-hidden rounded-full bg-muted">
          <div
            className="bg-emerald-500"
            style={{ width: `${validatedPct}%` }}
          />
          <div className="bg-red-400" style={{ width: `${errorsPct}%` }} />
        </div>
      </div>

      {/* Détails */}
      <Collapsible>
        <CollapsibleTrigger className="group flex w-full items-center justify-between rounded-lg border border-border px-3 py-2 text-sm text-muted-foreground hover:bg-muted/50 transition-colors">
          {i.details}
          <ChevronDown className="w-4 h-4 transition-transform group-data-[state=open]:rotate-180" />
        </CollapsibleTrigger>
        <CollapsibleContent>
          <div className="pt-3 space-y-3 text-sm">
            <div className="flex items-center gap-2 text-muted-foreground">
              <Mail className="w-3.5 h-3.5 shrink-0" />
              <span className="truncate">{installer.email}</span>
            </div>
            {archived && installer.archived_at ? (
              <div className="flex items-center gap-2 text-muted-foreground">
                <Archive className="w-3.5 h-3.5 shrink-0" />
                {i.archivedSince(formatDate(installer.archived_at, locale))}
              </div>
            ) : (
              installer.since && (
                <div className="flex items-center gap-2 text-muted-foreground">
                  <Clock className="w-3.5 h-3.5 shrink-0" />
                  {i.since(formatDate(installer.since, locale))}
                </div>
              )
            )}

            {installer.recent_installations.length > 0 && (
              <div>
                <p className="text-xs font-semibold text-foreground mb-1.5">
                  {i.recentTitle}
                </p>
                <div className="space-y-1">
                  {installer.recent_installations.map((r) => (
                    <div
                      key={r.id}
                      className="flex items-center gap-2 text-xs"
                    >
                      <span
                        className="w-2 h-2 rounded-full shrink-0"
                        style={{ backgroundColor: r.status_color }}
                      />
                      <span className="font-mono font-medium text-foreground">
                        {r.license_plate || i.noPlate}
                      </span>
                      <span className="text-muted-foreground truncate">
                        {r.device_label || i.deviceUnknown}
                      </span>
                      <span className="ml-auto text-muted-foreground shrink-0">
                        {r.date ? formatDate(r.date, locale) : "—"}
                      </span>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>
        </CollapsibleContent>
      </Collapsible>
    </div>
  );
}

export function InstallersList() {
  const t = useT();
  const locale = useLocale();
  const container = useRepositories();

  const [tab, setTab] = useState<Tab>("active");
  const [search, setSearch] = useState("");
  const [formOpen, setFormOpen] = useState(false);
  const [editing, setEditing] = useState<Installer | null>(null);
  const [passwordTarget, setPasswordTarget] = useState<Installer | null>(null);
  const [archiving, setArchiving] = useState<Installer | null>(null);
  const [restoring, setRestoring] = useState<Installer | null>(null);
  const [deleting, setDeleting] = useState<Installer | null>(null);

  const archived = tab === "archived";

  const { data: installers, loading, refetch } = useApiQuery(
    () => container.installerRepository.findAll(archived),
    { deps: [tab] }
  );

  const archiveMutation = useApiMutation(
    (id: number) => container.installerRepository.remove(id),
    {
      successMessage: t.installers.manage.archiveSuccess,
      onSuccess: () => {
        setArchiving(null);
        refetch();
      },
    }
  );

  const restoreMutation = useApiMutation(
    (id: number) => container.installerRepository.restore(id),
    {
      successMessage: t.installers.manage.restoreSuccess,
      onSuccess: () => {
        setRestoring(null);
        refetch();
      },
    }
  );

  const deleteMutation = useApiMutation(
    (id: number) => container.installerRepository.forceRemove(id),
    {
      successMessage: t.installers.manage.deleteSuccess,
      onSuccess: () => {
        setDeleting(null);
        refetch();
      },
    }
  );

  usePageHeader(
    t.pages.installers.title,
    t.pages.installers.subtitle(installers?.length ?? 0)
  );

  const openCreate = () => {
    setEditing(null);
    setFormOpen(true);
  };
  const openEdit = (installer: Installer) => {
    setEditing(installer);
    setFormOpen(true);
  };

  const filtered = useMemo(() => {
    const list = installers ?? [];
    const term = search.trim().toLowerCase();
    if (!term) return list;
    return list.filter(
      (i) =>
        i.name.toLowerCase().includes(term) ||
        i.email.toLowerCase().includes(term)
    );
  }, [installers, search]);

  const dialogs = (
    <>
      <InstallerFormDialog
        open={formOpen}
        onOpenChange={setFormOpen}
        installer={editing}
        onSuccess={refetch}
      />
      <InstallerPasswordDialog
        open={!!passwordTarget}
        onOpenChange={(open) => !open && setPasswordTarget(null)}
        installer={passwordTarget}
        onSuccess={refetch}
      />
      <AlertDialog
        open={!!archiving}
        onOpenChange={(open) => !open && setArchiving(null)}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>{t.installers.manage.archiveTitle}</AlertDialogTitle>
            <AlertDialogDescription>
              {archiving && t.installers.manage.archiveConfirm(archiving.name)}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>{t.installers.manage.cancel}</AlertDialogCancel>
            <AlertDialogAction
              disabled={archiveMutation.loading}
              onClick={(e) => {
                e.preventDefault();
                if (archiving) archiveMutation.mutate(archiving.id);
              }}
            >
              {t.installers.manage.archive}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
      <AlertDialog
        open={!!restoring}
        onOpenChange={(open) => !open && setRestoring(null)}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>{t.installers.manage.restore}</AlertDialogTitle>
            <AlertDialogDescription>
              {restoring && t.installers.manage.archiveConfirm(restoring.name)}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>{t.installers.manage.cancel}</AlertDialogCancel>
            <AlertDialogAction
              disabled={restoreMutation.loading}
              onClick={(e) => {
                e.preventDefault();
                if (restoring) restoreMutation.mutate(restoring.id);
              }}
            >
              {t.installers.manage.restore}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
      <AlertDialog
        open={!!deleting}
        onOpenChange={(open) => !open && setDeleting(null)}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>{t.installers.manage.deleteTitle}</AlertDialogTitle>
            <AlertDialogDescription>
              {deleting && t.installers.manage.deleteConfirm(deleting.name)}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>{t.installers.manage.cancel}</AlertDialogCancel>
            <AlertDialogAction
              disabled={deleteMutation.loading}
              onClick={(e) => {
                e.preventDefault();
                if (deleting) deleteMutation.mutate(deleting.id);
              }}
            >
              {t.installers.manage.deleteForever}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );

  const body = () => {
    if (loading) {
      return (
        <div className="flex items-center justify-center py-16">
          <Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
        </div>
      );
    }

    if (!installers || installers.length === 0) {
      return (
        <div className="flex flex-col items-center justify-center text-center py-16 px-6 bg-card border border-border rounded-xl">
          <div className="w-16 h-16 rounded-full bg-primary/10 flex items-center justify-center mb-4">
            <Users className="w-8 h-8 text-primary" />
          </div>
          <p className="text-base font-semibold text-foreground">
            {archived ? t.installers.archivedEmpty : t.installers.empty}
          </p>
          <p className="text-sm text-muted-foreground mt-1 max-w-xs">
            {archived ? t.installers.archivedEmptyHint : t.installers.emptyHint}
          </p>
          {!archived && (
            <Button className="mt-5" onClick={openCreate}>
              <Plus className="w-4 h-4 mr-2" />
              {t.installers.manage.add}
            </Button>
          )}
        </div>
      );
    }

    return (
      <div className="space-y-4">
        <div className="flex items-center gap-3">
          <div className="relative flex-1">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
            <Input
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              placeholder={t.installers.searchPlaceholder}
              className="pl-9"
            />
          </div>
          {!archived && (
            <Button className="shrink-0" onClick={openCreate}>
              <Plus className="w-4 h-4 mr-2" />
              {t.installers.manage.add}
            </Button>
          )}
        </div>

        {filtered.length === 0 ? (
          <div className="text-center py-12 text-sm text-muted-foreground">
            {t.installers.noResults}
          </div>
        ) : (
          <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
            {filtered.map((installer) => (
              <InstallerCard
                key={installer.id}
                installer={installer}
                locale={locale}
                archived={archived}
                onEdit={openEdit}
                onChangePassword={setPasswordTarget}
                onArchive={setArchiving}
                onRestore={setRestoring}
                onForceDelete={setDeleting}
              />
            ))}
          </div>
        )}
      </div>
    );
  };

  return (
    <div className="space-y-4">
      <Tabs value={tab} onValueChange={(v) => setTab(v as Tab)}>
        <TabsList>
          <TabsTrigger value="active">{t.installers.tabs.active}</TabsTrigger>
          <TabsTrigger value="archived">
            {t.installers.tabs.archived}
          </TabsTrigger>
        </TabsList>
        <TabsContent value="active" className="mt-4">
          {!archived && body()}
        </TabsContent>
        <TabsContent value="archived" className="mt-4">
          {archived && body()}
        </TabsContent>
      </Tabs>

      {dialogs}
    </div>
  );
}
