"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { useForm, useFieldArray, Controller } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { toast } from "sonner";
import {
  Plus, Trash2, ArrowLeft, Loader2, Send, Save,
} from "lucide-react";
import { DescriptionCombobox } from "@/components/invoice/description-combobox";
import { useTaxRates } from "@/hooks/use-tax-rates";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
  Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from "@/components/ui/select";
import { Separator } from "@/components/ui/separator";
import { Textarea } from "@/components/ui/textarea";
import { cn, formatCurrency } from "@/lib/utils";

// ─── Schéma de validation ────────────────────────────────────

const itemSchema = z.object({
  description: z.string().min(1, "Description requise"),
  quantity: z.coerce.number().positive("Quantité invalide"),
  unitPrice: z.coerce.number().min(0, "Prix invalide"),
  taxRate: z.coerce.number().min(0).max(100),
});

const formSchema = z.object({
  customerId: z.string().optional(),
  issueDate: z.string().min(1, "Date d'émission requise"),
  dueDate: z.string().optional(),
  currency: z.string().default("XOF"),
  notes: z.string().optional(),
  terms: z.string().optional(),
  items: z.array(itemSchema).min(1, "Au moins un article est requis"),
});

type FormValues = z.infer<typeof formSchema>;

// ─── Types ────────────────────────────────────────────────────

type Customer = {
  id: string;
  name: string;
  email: string | null;
};

type Product = {
  id: string;
  name: string;
  description: string | null;
  reference: string | null;
  unitPrice: number;
  taxRate: number;
  unit: string | null;
  category: string | null;
};


function today(): string {
  return new Date().toISOString().split("T")[0];
}

function in30Days(): string {
  const d = new Date();
  d.setDate(d.getDate() + 30);
  return d.toISOString().split("T")[0];
}

// ─── Composant ligne article ──────────────────────────────────

function ItemRow({
  index,
  control,
  register,
  errors,
  onRemove,
  canRemove,
  watch,
  onSelectProduct,
  taxRates,
}: {
  index: number;
  control: any;
  register: any;
  errors: any;
  onRemove: () => void;
  canRemove: boolean;
  watch: any;
  onSelectProduct: (p: Product) => void;
  taxRates: { rate: number; name: string }[];
}) {
  const qty = parseFloat(watch(`items.${index}.quantity`) || "0");
  const price = parseFloat(watch(`items.${index}.unitPrice`) || "0");
  const taxRate = parseFloat(watch(`items.${index}.taxRate`) || "0");

  const baseHT = isNaN(qty) || isNaN(price) ? 0 : qty * price;

  // Récupère la valeur description pour le combobox
  const descValue = watch(`items.${index}.description`) ?? "";

  return (
    <div className="grid grid-cols-12 gap-2 items-start py-3 border-b last:border-0">
      {/* Description avec autocomplétion */}
      <div className="col-span-12 sm:col-span-4">
        <Controller
          control={control}
          name={`items.${index}.description`}
          render={({ field }) => (
            <DescriptionCombobox
              value={field.value ?? ""}
              onChange={field.onChange}
              onSelectProduct={onSelectProduct}
              error={!!errors?.items?.[index]?.description}
            />
          )}
        />
        {errors?.items?.[index]?.description && (
          <p className="text-xs text-destructive mt-1">
            {errors.items[index].description.message}
          </p>
        )}
      </div>

      {/* Quantité */}
      <div className="col-span-4 sm:col-span-2">
        <Input
          type="number"
          min="0.01"
          step="0.01"
          placeholder="Qté"
          {...register(`items.${index}.quantity`)}
          className={cn(errors?.items?.[index]?.quantity && "border-destructive")}
        />
      </div>

      {/* Prix HT */}
      <div className="col-span-4 sm:col-span-2">
        <Input
          type="number"
          min="0"
          step="0.01"
          placeholder="Prix HT"
          {...register(`items.${index}.unitPrice`)}
          className={cn(errors?.items?.[index]?.unitPrice && "border-destructive")}
        />
      </div>

      {/* TVA */}
      <div className="col-span-4 sm:col-span-2">
        <Controller
          control={control}
          name={`items.${index}.taxRate`}
          render={({ field }) => (
            <Select
              value={String(field.value)}
              onValueChange={(v) => field.onChange(parseFloat(v))}
            >
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                {taxRates.map((t) => (
                  <SelectItem key={t.rate} value={String(t.rate)}>
                    {t.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          )}
        />
      </div>

      {/* Total HT */}
      <div className="col-span-10 sm:col-span-1 flex items-center justify-end">
        <span className="text-sm font-semibold tabular-nums text-right">
          {formatCurrency(baseHT)}
        </span>
      </div>

      {/* Supprimer */}
      <div className="col-span-2 sm:col-span-1 flex items-center justify-end">
        <Button
          type="button"
          variant="ghost"
          size="icon"
          className="h-9 w-9 text-muted-foreground hover:text-destructive"
          onClick={onRemove}
          disabled={!canRemove}
        >
          <Trash2 className="h-4 w-4" />
        </Button>
      </div>
    </div>
  );
}

// ─── Page principale ──────────────────────────────────────────

export default function NouvelleFacturePage() {
  const router = useRouter();
  const [customers, setCustomers] = useState<Customer[]>([]);
  const [loadingCustomers, setLoadingCustomers] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [sendAfterSave, setSendAfterSave] = useState(false);
  const { taxRates, defaultRate } = useTaxRates();


  const {
    register,
    control,
    handleSubmit,
    watch,
    formState: { errors },
  } = useForm<FormValues>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      issueDate: today(),
      dueDate: in30Days(),
      currency: "XOF",
      items: [{ description: "", quantity: 1, unitPrice: 0, taxRate: defaultRate }],
    },
  });

  const { fields, append, remove, update } = useFieldArray({ control, name: "items" });
  const watchedItems = watch("items");

  function handleSelectProduct(index: number, product: Product) {
    update(index, {
      description: product.name + (product.description ? ` — ${product.description}` : ""),
      quantity: 1,
      unitPrice: Number(product.unitPrice),
      taxRate: Number(product.taxRate),
    });
  }

  // Totaux récapitulatifs
  const totals = watchedItems.reduce(
    (acc, item) => {
      const qty = parseFloat(String(item.quantity)) || 0;
      const price = parseFloat(String(item.unitPrice)) || 0;
      const tax = parseFloat(String(item.taxRate)) || 0;
      const ht = qty * price;
      const tva = ht * (tax / 100);
      return {
        subtotalHT: acc.subtotalHT + ht,
        totalTVA: acc.totalTVA + tva,
        totalTTC: acc.totalTTC + ht + tva,
      };
    },
    { subtotalHT: 0, totalTVA: 0, totalTTC: 0 }
  );

  // Charger les clients
  useEffect(() => {
    async function fetchCustomers() {
      try {
        const res = await fetch("/api/customers?limit=100");
        const json = await res.json();
        if (json.success) setCustomers(json.data ?? []);
      } catch {
        // silencieux
      } finally {
        setLoadingCustomers(false);
      }
    }
    fetchCustomers();
  }, []);

  async function onSubmit(values: FormValues) {
    setSubmitting(true);
    try {
      const res = await fetch("/api/invoices", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(values),
      });
      const json = await res.json();
      if (!res.ok) throw new Error(json.error ?? "Erreur lors de la création");

      const invoiceId = json.data?.id;

      // Envoyer après sauvegarde si demandé
      if (sendAfterSave && invoiceId) {
        const sendRes = await fetch(`/api/invoices/${invoiceId}/send`, { method: "POST" });
        if (sendRes.ok) {
          toast.success("Facture créée et envoyée avec succès");
        } else {
          toast.success("Facture créée. L'envoi a échoué, veuillez réessayer depuis le détail.");
        }
      } else {
        toast.success("Facture enregistrée comme brouillon");
      }

      router.push("/factures");
    } catch (err: any) {
      toast.error(err.message ?? "Une erreur est survenue");
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <div className="space-y-6 max-w-5xl mx-auto">
      {/* En-tête */}
      <div className="flex items-center gap-4">
        <Button
          variant="ghost"
          size="icon"
          className="h-9 w-9"
          onClick={() => router.back()}
        >
          <ArrowLeft className="h-4 w-4" />
        </Button>
        <div>
          <h1 className="text-2xl font-bold tracking-tight">Nouvelle facture</h1>
          <p className="text-sm text-muted-foreground">
            Remplissez les informations ci-dessous pour créer une facture
          </p>
        </div>
      </div>

      <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
        {/* Informations générales */}
        <Card>
          <CardHeader>
            <CardTitle className="text-base">Informations générales</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              {/* Client */}
              <div className="space-y-1.5">
                <Label>Client</Label>
                <Controller
                  control={control}
                  name="customerId"
                  render={({ field }) => (
                    <Select
                      value={field.value ?? ""}
                      onValueChange={(v) => field.onChange(v === "none" ? undefined : v)}
                      disabled={loadingCustomers}
                    >
                      <SelectTrigger>
                        <SelectValue
                          placeholder={
                            loadingCustomers ? "Chargement…" : "Sélectionner un client"
                          }
                        />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="none">Aucun client</SelectItem>
                        {customers.map((c) => (
                          <SelectItem key={c.id} value={c.id}>
                            {c.name}
                            {c.email && (
                              <span className="text-muted-foreground ml-2 text-xs">
                                {c.email}
                              </span>
                            )}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  )}
                />
              </div>

              {/* Devise */}
              <div className="space-y-1.5">
                <Label>Devise</Label>
                <Controller
                  control={control}
                  name="currency"
                  render={({ field }) => (
                    <Select value={field.value} onValueChange={field.onChange}>
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="XOF">XOF — Franc CFA (UEMOA)</SelectItem>
                        <SelectItem value="XAF">XAF — Franc CFA (CEMAC)</SelectItem>
                        <SelectItem value="EUR">EUR — Euro</SelectItem>
                        <SelectItem value="USD">USD — Dollar américain</SelectItem>
                        <SelectItem value="GBP">GBP — Livre sterling</SelectItem>
                        <SelectItem value="CHF">CHF — Franc suisse</SelectItem>
                      </SelectContent>
                    </Select>
                  )}
                />
              </div>

              {/* Date d'émission */}
              <div className="space-y-1.5">
                <Label htmlFor="issueDate">Date d'émission</Label>
                <Input
                  id="issueDate"
                  type="date"
                  {...register("issueDate")}
                  className={cn(errors.issueDate && "border-destructive")}
                />
                {errors.issueDate && (
                  <p className="text-xs text-destructive">{errors.issueDate.message}</p>
                )}
              </div>

              {/* Date d'échéance */}
              <div className="space-y-1.5">
                <Label htmlFor="dueDate">Date d'échéance</Label>
                <Input id="dueDate" type="date" {...register("dueDate")} />
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Articles */}
        <Card>
          <CardHeader>
            <div className="flex items-center justify-between">
              <CardTitle className="text-base">Articles</CardTitle>
              <Button
                type="button"
                variant="outline"
                size="sm"
                onClick={() => append({ description: "", quantity: 1, unitPrice: 0, taxRate: 20 })}
              >
                <Plus className="h-4 w-4" />
                Ajouter une ligne
              </Button>
            </div>
          </CardHeader>
          <CardContent className="p-0">
            {/* En-têtes colonnes */}
            <div className="hidden sm:grid grid-cols-12 gap-2 px-6 pb-2 pt-4 text-xs font-medium text-muted-foreground uppercase tracking-wide border-b">
              <div className="col-span-4">Description</div>
              <div className="col-span-2">Quantité</div>
              <div className="col-span-2">Prix HT</div>
              <div className="col-span-2">TVA</div>
              <div className="col-span-1 text-right">Total HT</div>
              <div className="col-span-1" />
            </div>

            <div className="px-6">
              {fields.map((field, index) => (
                <ItemRow
                  key={field.id}
                  index={index}
                  control={control}
                  register={register}
                  errors={errors}
                  watch={watch}
                  onRemove={() => remove(index)}
                  canRemove={fields.length > 1}
                  onSelectProduct={(p) => handleSelectProduct(index, p)}
                  taxRates={taxRates}
                />
              ))}
            </div>

            {errors.items?.root && (
              <p className="text-xs text-destructive px-6 pb-4">
                {errors.items.root.message}
              </p>
            )}

            {errors.items && !Array.isArray(errors.items) && (
              <p className="text-xs text-destructive px-6 pb-4">
                {(errors.items as any).message}
              </p>
            )}

            {/* Récapitulatif */}
            <div className="px-6 pb-6 mt-4">
              <Separator className="mb-4" />
              <div className="flex justify-end">
                <div className="w-full max-w-xs space-y-2">
                  <div className="flex justify-between text-sm">
                    <span className="text-muted-foreground">Sous-total HT</span>
                    <span className="font-medium tabular-nums">
                      {formatCurrency(totals.subtotalHT)}
                    </span>
                  </div>
                  <div className="flex justify-between text-sm">
                    <span className="text-muted-foreground">TVA</span>
                    <span className="font-medium tabular-nums">
                      {formatCurrency(totals.totalTVA)}
                    </span>
                  </div>
                  <Separator />
                  <div className="flex justify-between text-base font-bold">
                    <span>Total TTC</span>
                    <span className="tabular-nums text-primary">
                      {formatCurrency(totals.totalTTC)}
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Notes & Conditions */}
        <Card>
          <CardHeader>
            <CardTitle className="text-base">Notes et conditions</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="space-y-1.5">
              <Label htmlFor="notes">Notes</Label>
              <Textarea
                id="notes"
                rows={3}
                placeholder="Notes visibles sur la facture (optionnel)"
                {...register("notes")}
              />
            </div>
            <div className="space-y-1.5">
              <Label htmlFor="terms">Conditions de paiement</Label>
              <Textarea
                id="terms"
                rows={3}
                placeholder="Ex. : Paiement à 30 jours. Pénalités de retard : 3× le taux légal. (optionnel)"
                {...register("terms")}
              />
            </div>
          </CardContent>
        </Card>

        {/* Actions */}
        <div className="flex items-center justify-between gap-3 pt-2 flex-wrap">
          <Button
            type="button"
            variant="outline"
            onClick={() => router.back()}
            disabled={submitting}
          >
            Annuler
          </Button>

          <div className="flex items-center gap-3">
            <Button
              type="submit"
              variant="outline"
              disabled={submitting}
              onClick={() => setSendAfterSave(false)}
            >
              {submitting && !sendAfterSave ? (
                <Loader2 className="h-4 w-4 animate-spin" />
              ) : (
                <Save className="h-4 w-4" />
              )}
              Enregistrer brouillon
            </Button>

            <Button
              type="submit"
              disabled={submitting}
              onClick={() => setSendAfterSave(true)}
            >
              {submitting && sendAfterSave ? (
                <Loader2 className="h-4 w-4 animate-spin" />
              ) : (
                <Send className="h-4 w-4" />
              )}
              Enregistrer et envoyer
            </Button>
          </div>
        </div>
      </form>
    </div>
  );
}
