"use client";

import { useCallback, useMemo, useState } from "react";
import { useForm, useFieldArray } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import {
  Boxes,
  Package,
  PackageX,
  CircleDollarSign,
  MoreHorizontal,
  Plus,
  Loader2,
  Trash2,
  Pencil,
} 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 { useDeleteTarget } from "@/presentation/hooks/use-delete-target";
import { useServerPagination } from "@/presentation/hooks/use-server-pagination";
import { useT, useLocale } from "@/shared/i18n/client";
import ServerDataTable from "@/presentation/components/shared/server-data-table";
import StatsCard from "@/presentation/components/shared/stats-card";
import ConfirmationDialog from "@/presentation/components/shared/confirmation-dialog";
import { Button } from "@/presentation/components/ui/button";
import { Badge } from "@/presentation/components/ui/badge";
import { Input } from "@/presentation/components/ui/input";
import { Checkbox } from "@/presentation/components/ui/checkbox";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/presentation/components/ui/select";
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/presentation/components/ui/dialog";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/presentation/components/ui/dropdown-menu";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/presentation/components/ui/form";
import {
  telematicsProductSchema,
  type TelematicsProductFormValues,
} from "@/shared/schemas/telematics-product.schema";
import {
  TELEMATICS_NEEDS_SUGGESTIONS,
  TELEMATICS_PRODUCT_CATEGORIES,
  type TelematicsProduct,
  type TelematicsProductCategory,
} from "@/domain/entities/telematics-product";
import type { Column } from "@/presentation/components/shared/server-data-table";

const PRODUCT_DEFAULTS: TelematicsProductFormValues = {
  sku: "",
  category: "boitier",
  name: "",
  description: "",
  price: 0,
  stock_quantity: 0,
  is_active: true,
  needs_covered: [],
  specifications: [],
};

export function CatalogTab() {
  const t = useT();
  const locale = useLocale();
  const container = useRepositories();
  const repo = container.telematicsCatalogRepository;
  const pagination = useServerPagination({ orderBy: "name", order: "ASC" });

  const [dialogOpen, setDialogOpen] = useState(false);
  const [editing, setEditing] = useState<TelematicsProduct | null>(null);
  const [customNeed, setCustomNeed] = useState("");
  const deleteDialog = useDeleteTarget<TelematicsProduct>();

  const { data: stats, refetch: refetchStats } = useApiQuery(
    () => repo.getStats(),
    { deps: [] }
  );
  const { data: response, loading, refetch } = useApiQuery(
    () => repo.findAll(pagination.params),
    { deps: [pagination.params] }
  );
  const { data: needsSuggestions } = useApiQuery(
    () => repo.getNeedsSuggestions(),
    { deps: [] }
  );

  const refreshAll = useCallback(() => {
    refetch();
    refetchStats();
  }, [refetch, refetchStats]);

  const schema = useMemo(() => telematicsProductSchema(t), [t]);
  const form = useForm<TelematicsProductFormValues>({
    resolver: zodResolver(schema),
    defaultValues: PRODUCT_DEFAULTS,
  });
  const specs = useFieldArray({ control: form.control, name: "specifications" });
  const selectedNeeds = form.watch("needs_covered");

  const createMutation = useApiMutation(
    (data: TelematicsProductFormValues) => repo.create(data),
    {
      successMessage: t.telematics.catalog.toasts.created,
      onSuccess: () => {
        setDialogOpen(false);
        refreshAll();
      },
    }
  );

  const updateMutation = useApiMutation(
    ({ id, data }: { id: number; data: TelematicsProductFormValues }) =>
      repo.update(id, data),
    {
      successMessage: t.telematics.catalog.toasts.updated,
      onSuccess: () => {
        setDialogOpen(false);
        setEditing(null);
        refreshAll();
      },
    }
  );

  const deleteMutation = useApiMutation((id: number) => repo.delete(id), {
    successMessage: t.telematics.catalog.toasts.deleted,
    onSuccess: () => {
      deleteDialog.close();
      refreshAll();
    },
  });

  const openCreate = useCallback(() => {
    setEditing(null);
    form.reset(PRODUCT_DEFAULTS);
    setDialogOpen(true);
  }, [form]);

  const openEdit = useCallback(
    (p: TelematicsProduct) => {
      setEditing(p);
      form.reset({
        sku: p.sku,
        category: p.category,
        name: p.name,
        description: p.description ?? "",
        price: p.price,
        stock_quantity: p.stock_quantity,
        is_active: p.is_active,
        needs_covered: p.needs_covered,
        specifications: p.specifications,
      });
      setDialogOpen(true);
    },
    [form]
  );

  const toggleNeed = (need: string) => {
    const current = form.getValues("needs_covered");
    form.setValue(
      "needs_covered",
      current.includes(need) ? current.filter((n) => n !== need) : [...current, need],
      { shouldValidate: true }
    );
  };

  const addCustomNeed = () => {
    const v = customNeed.trim();
    if (!v) return;
    const current = form.getValues("needs_covered");
    if (!current.includes(v)) {
      form.setValue("needs_covered", [...current, v], { shouldValidate: true });
    }
    setCustomNeed("");
  };

  const onSubmit = async (values: TelematicsProductFormValues) => {
    if (editing) {
      await updateMutation.mutate({ id: editing.id, data: values });
    } else {
      await createMutation.mutate(values);
    }
  };

  const formatMoney = (value: number) =>
    new Intl.NumberFormat(locale === "fr" ? "fr-FR" : "en-US", {
      style: "currency",
      currency: "EUR",
      maximumFractionDigits: 0,
    }).format(value);

  // Server-provided suggestions (falls back to the hardcoded list if unreachable)
  // unioned with any currently-selected custom needs the user added.
  const allKnownNeeds = useMemo(() => {
    const base =
      needsSuggestions && needsSuggestions.length > 0
        ? needsSuggestions
        : TELEMATICS_NEEDS_SUGGESTIONS;
    const set = new Set(base);
    selectedNeeds?.forEach((n) => set.add(n));
    return Array.from(set);
  }, [needsSuggestions, selectedNeeds]);

  const columns: Column<TelematicsProduct>[] = [
    {
      key: "sku",
      label: t.telematics.catalog.columns.sku,
      sortable: true,
      render: (row) => (
        <span className="font-mono text-xs">{row.sku}</span>
      ),
    },
    {
      key: "name",
      label: t.telematics.catalog.columns.product,
      sortable: true,
      truncate: true,
      render: (row) => (
        <div>
          <p className="font-medium text-foreground">{row.name}</p>
          {row.description && (
            <p className="text-xs text-muted-foreground truncate">
              {row.description}
            </p>
          )}
        </div>
      ),
    },
    {
      key: "category",
      label: t.telematics.catalog.columns.category,
      render: (row) => (
        <span className="text-xs">
          {t.telematics.catalog.categories[row.category]}
        </span>
      ),
    },
    {
      key: "needs_covered",
      label: t.telematics.catalog.columns.needs,
      render: (row) => (
        <div className="flex flex-wrap gap-1 max-w-xs">
          {row.needs_covered.slice(0, 4).map((n) => (
            <Badge key={n} variant="secondary" className="text-[10px] px-1.5 py-0">
              {n}
            </Badge>
          ))}
          {row.needs_covered.length > 4 && (
            <Badge variant="secondary" className="text-[10px] px-1.5 py-0">
              +{row.needs_covered.length - 4}
            </Badge>
          )}
        </div>
      ),
    },
    {
      key: "price",
      label: t.telematics.catalog.columns.price,
      sortable: true,
      render: (row) => (
        <span className="text-xs font-medium">{formatMoney(row.price)}</span>
      ),
    },
    {
      key: "stock_quantity",
      label: t.telematics.catalog.columns.stock,
      sortable: true,
      render: (row) => (
        <span
          className={`text-xs font-medium ${
            row.stock_quantity === 0 ? "text-destructive" : ""
          }`}
        >
          {row.stock_quantity}
        </span>
      ),
    },
    {
      key: "is_active",
      label: t.telematics.catalog.columns.status,
      render: (row) => (
        <Badge
          className={`border-0 text-xs ${
            row.is_active
              ? "bg-emerald-50 text-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-400"
              : "bg-gray-100 text-gray-600 dark:bg-gray-800/40 dark:text-gray-400"
          }`}
        >
          {row.is_active ? t.common.active : t.common.inactive}
        </Badge>
      ),
    },
    {
      key: "actions",
      label: "",
      className: "w-10",
      render: (row) => (
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="ghost" size="icon-sm">
              <MoreHorizontal className="w-4 h-4" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            <DropdownMenuItem onClick={() => openEdit(row)}>
              <Pencil className="w-4 h-4 mr-2" />
              {t.common.edit}
            </DropdownMenuItem>
            <DropdownMenuSeparator />
            <DropdownMenuItem
              className="text-destructive"
              onClick={() => deleteDialog.open(row)}
            >
              <Trash2 className="w-4 h-4 mr-2" />
              {t.common.delete}
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      ),
    },
  ];

  return (
    <div className="space-y-6">
      <div className="flex items-start justify-between gap-4">
        <p className="text-sm text-muted-foreground">
          {t.telematics.catalog.subtitle}
        </p>
        <Button onClick={openCreate} className="shrink-0">
          <Plus className="w-4 h-4 mr-1" />
          {t.telematics.catalog.addButton}
        </Button>
      </div>

      {stats && (
        <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
          <StatsCard
            title={t.telematics.catalog.stats.products}
            value={stats.products}
            icon={Boxes}
            accent="blue"
          />
          <StatsCard
            title={t.telematics.catalog.stats.active}
            value={stats.active}
            icon={Package}
            accent="green"
          />
          <StatsCard
            title={t.telematics.catalog.stats.outOfStock}
            value={stats.out_of_stock}
            icon={PackageX}
            accent="purple"
          />
          <StatsCard
            title={t.telematics.catalog.stats.stockValue}
            value={formatMoney(stats.stock_value)}
            icon={CircleDollarSign}
            accent="amber"
            mono
          />
        </div>
      )}

      <ServerDataTable
        columns={columns}
        data={response?.items ?? []}
        total={response?.total ?? 0}
        page={pagination.page}
        totalPages={response?.last_page ?? 1}
        loading={loading}
        search={pagination.search}
        onSearchChange={pagination.setSearch}
        onPageChange={pagination.setPage}
        onSortChange={pagination.setSort}
        sortBy={pagination.orderBy}
        sortOrder={pagination.order}
        searchPlaceholder={t.telematics.catalog.searchPlaceholder}
        emptyMessage={t.telematics.catalog.empty}
        toolbar={
          <div className="flex flex-col gap-1">
            <span className="text-[11px] font-medium text-muted-foreground leading-none">
              {t.telematics.catalog.filters.category}
            </span>
            <Select
              value={(pagination.filters.category as string) ?? "all"}
              onValueChange={(v) =>
                pagination.setFilter("category", v === "all" ? undefined : v)
              }
            >
              <SelectTrigger className="h-8 w-44 text-xs">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">
                  {t.telematics.catalog.filters.allCategories}
                </SelectItem>
                {TELEMATICS_PRODUCT_CATEGORIES.map((c) => (
                  <SelectItem key={c} value={c}>
                    {t.telematics.catalog.categories[c]}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        }
      />

      {/* Product dialog */}
      <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
        <DialogContent
          className="max-w-2xl max-h-[90vh] overflow-y-auto"
          onOpenAutoFocus={(e) => e.preventDefault()}
        >
          <DialogHeader>
            <DialogTitle>
              {editing
                ? t.telematics.catalog.dialog.titleEdit
                : t.telematics.catalog.dialog.titleCreate}
            </DialogTitle>
          </DialogHeader>
          <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <FormField
                  control={form.control}
                  name="sku"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>{t.telematics.catalog.fields.sku}</FormLabel>
                      <FormControl>
                        <Input
                          {...field}
                          placeholder={t.telematics.catalog.fields.skuPlaceholder}
                          onFocus={(e) => e.target.select()}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="category"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>{t.telematics.catalog.fields.category}</FormLabel>
                      <FormControl>
                        <Select
                          value={field.value}
                          onValueChange={(v) =>
                            field.onChange(v as TelematicsProductCategory)
                          }
                        >
                          <SelectTrigger className="w-full">
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            {TELEMATICS_PRODUCT_CATEGORIES.map((c) => (
                              <SelectItem key={c} value={c}>
                                {t.telematics.catalog.categories[c]}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>

              <FormField
                control={form.control}
                name="name"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{t.telematics.catalog.fields.name}</FormLabel>
                    <FormControl>
                      <Input
                        {...field}
                        placeholder={t.telematics.catalog.fields.namePlaceholder}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="description"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{t.telematics.catalog.fields.description}</FormLabel>
                    <FormControl>
                      <textarea
                        className="flex min-h-[90px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-xs placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <div className="grid grid-cols-3 gap-4 items-end">
                <FormField
                  control={form.control}
                  name="price"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>{t.telematics.catalog.fields.priceHt}</FormLabel>
                      <FormControl>
                        <Input
                          type="number"
                          step="0.01"
                          onFocus={(e) => e.target.select()}
                          {...field}
                          onChange={(e) => field.onChange(e.target.valueAsNumber)}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="stock_quantity"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>{t.telematics.catalog.fields.stock}</FormLabel>
                      <FormControl>
                        <Input
                          type="number"
                          onFocus={(e) => e.target.select()}
                          {...field}
                          onChange={(e) => field.onChange(e.target.valueAsNumber)}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="is_active"
                  render={({ field }) => (
                    <FormItem className="flex flex-row items-center gap-2 rounded-md border border-input px-3 h-9">
                      <FormControl>
                        <Checkbox
                          checked={field.value}
                          onCheckedChange={(v) => field.onChange(v === true)}
                        />
                      </FormControl>
                      <FormLabel className="mb-0 font-normal text-sm">
                        {t.telematics.catalog.fields.statusActive}
                      </FormLabel>
                    </FormItem>
                  )}
                />
              </div>

              {/* Needs covered */}
              <div className="space-y-2">
                <FormLabel className="text-xs uppercase tracking-wider">
                  {t.telematics.catalog.fields.needsCovered}
                </FormLabel>
                <p className="text-xs text-muted-foreground">
                  {t.telematics.catalog.fields.needsHelp}
                </p>
                <div className="flex flex-wrap gap-2">
                  {allKnownNeeds.map((n) => {
                    const active = selectedNeeds?.includes(n);
                    return (
                      <button
                        type="button"
                        key={n}
                        onClick={() => toggleNeed(n)}
                        className={`text-xs rounded-full px-3 py-1 border transition-colors ${
                          active
                            ? "bg-primary text-primary-foreground border-primary"
                            : "bg-transparent border-border text-muted-foreground hover:bg-muted"
                        }`}
                      >
                        {n}
                      </button>
                    );
                  })}
                </div>
                <div className="flex gap-2">
                  <Input
                    value={customNeed}
                    placeholder={t.telematics.catalog.fields.addCustomNeed}
                    onChange={(e) => setCustomNeed(e.target.value)}
                    onKeyDown={(e) => {
                      if (e.key === "Enter") {
                        e.preventDefault();
                        addCustomNeed();
                      }
                    }}
                  />
                  <Button type="button" variant="outline" onClick={addCustomNeed}>
                    {t.telematics.catalog.fields.addNeedButton}
                  </Button>
                </div>
              </div>

              {/* Specifications */}
              <div className="space-y-2">
                <div className="flex items-center justify-between">
                  <FormLabel className="text-xs uppercase tracking-wider mb-0">
                    {t.telematics.catalog.fields.specifications}
                  </FormLabel>
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={() => specs.append({ key: "", value: "" })}
                  >
                    <Plus className="w-3.5 h-3.5 mr-1" />
                    {t.telematics.catalog.fields.addSpec}
                  </Button>
                </div>
                {specs.fields.map((f, idx) => (
                  <div key={f.id} className="grid grid-cols-[1fr_1fr_auto] gap-2">
                    <Input
                      placeholder={t.telematics.catalog.fields.specKeyPlaceholder}
                      {...form.register(`specifications.${idx}.key` as const)}
                    />
                    <Input
                      placeholder={t.telematics.catalog.fields.specValuePlaceholder}
                      {...form.register(`specifications.${idx}.value` as const)}
                    />
                    <Button
                      type="button"
                      variant="ghost"
                      size="icon"
                      onClick={() => specs.remove(idx)}
                    >
                      <Trash2 className="w-4 h-4" />
                    </Button>
                  </div>
                ))}
              </div>

              <DialogFooter>
                <Button
                  type="button"
                  variant="outline"
                  onClick={() => setDialogOpen(false)}
                >
                  {t.common.cancel}
                </Button>
                <Button
                  type="submit"
                  disabled={createMutation.loading || updateMutation.loading}
                >
                  {(createMutation.loading || updateMutation.loading) && (
                    <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                  )}
                  {editing
                    ? t.telematics.catalog.dialog.submitEdit
                    : t.telematics.catalog.dialog.submitCreate}
                </Button>
              </DialogFooter>
            </form>
          </Form>
        </DialogContent>
      </Dialog>

      <ConfirmationDialog
        open={deleteDialog.isOpen}
        onOpenChange={(open) => !open && deleteDialog.close()}
        title={t.telematics.catalog.delete.title}
        description={t.telematics.catalog.delete.description(
          deleteDialog.target?.name
        )}
        confirmLabel={t.common.delete}
        variant="destructive"
        loading={deleteMutation.loading}
        onConfirm={() =>
          deleteDialog.target && deleteMutation.mutate(deleteDialog.target.id)
        }
      />
    </div>
  );
}
