"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { ArrowLeft, Sparkles, Loader2, Upload, X } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
  Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from "@/components/ui/select";
import { Badge } from "@/components/ui/badge";
import { toast } from "sonner";
import { cn } from "@/lib/utils";
import { format } from "date-fns";

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

type Category = {
  id: string;
  name: string;
  color: string;
  icon?: string | null;
};

type AiResult = {
  categoryId: string | null;
  categoryName: string;
  confidence: number;
  explanation: string;
};

// ─── Constantes ───────────────────────────────────────────────

const TAX_RATES = [
  { value: "0", label: "0% — Exonéré" },
  { value: "5.5", label: "5,5% — Taux réduit" },
  { value: "10", label: "10% — Taux intermédiaire" },
  { value: "20", label: "20% — Taux normal" },
];

const PAYMENT_METHODS = [
  { value: "BANK_TRANSFER", label: "Virement bancaire" },
  { value: "CREDIT_CARD", label: "Carte bancaire" },
  { value: "CASH", label: "Espèces" },
  { value: "CHECK", label: "Chèque" },
  { value: "PAYPAL", label: "PayPal" },
  { value: "STRIPE", label: "Stripe" },
  { value: "OTHER", label: "Autre" },
];

// ─── Page création dépense ────────────────────────────────────

export default function NouvelleDepensePage() {
  const router = useRouter();

  // Catégories
  const [categories, setCategories] = useState<Category[]>([]);

  // Formulaire
  const [title, setTitle] = useState("");
  const [description, setDescription] = useState("");
  const [amount, setAmount] = useState("");
  const [taxRate, setTaxRate] = useState("20");
  const [categoryId, setCategoryId] = useState("");
  const [supplierId, setSupplierId] = useState("");
  const [date, setDate] = useState(format(new Date(), "yyyy-MM-dd"));
  const [paymentMethod, setPaymentMethod] = useState("");
  const [reference, setReference] = useState("");
  const [notes, setNotes] = useState("");
  const [receipt, setReceipt] = useState<File | null>(null);

  // États UI
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isCategorizing, setIsCategorizing] = useState(false);
  const [aiResult, setAiResult] = useState<AiResult | null>(null);

  // Chargement catégories
  useEffect(() => {
    fetch("/api/expenses/categories")
      .then((r) => r.json())
      .then((json) => {
        if (json.success) setCategories(json.data);
      })
      .catch(() => {});
  }, []);

  // Calcul TVA
  const amountNum = parseFloat(amount) || 0;
  const taxRateNum = parseFloat(taxRate) || 0;
  const taxAmount = Math.round(amountNum * (taxRateNum / 100) * 100) / 100;
  const totalTTC = Math.round((amountNum + taxAmount) * 100) / 100;

  // ─── Catégorisation IA ───────────────────────────────────
  const handleCategorizeAI = async () => {
    if (!description && !title) {
      toast.error("Renseignez un titre ou une description pour la catégorisation IA");
      return;
    }
    if (!amountNum) {
      toast.error("Renseignez un montant pour la catégorisation IA");
      return;
    }

    setIsCategorizing(true);
    setAiResult(null);
    try {
      const res = await fetch("/api/ai/categorize", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          description: description || title,
          amount: amountNum,
        }),
      });
      const json = await res.json();
      if (json.success) {
        setAiResult(json.data);
        if (json.data.categoryId) {
          setCategoryId(json.data.categoryId);
          toast.success(`Catégorie suggérée : ${json.data.categoryName}`);
        } else {
          toast.info(`IA : "${json.data.categoryName}" — catégorie non trouvée dans la liste`);
        }
      } else {
        toast.error(json.error ?? "Erreur lors de la catégorisation IA");
      }
    } catch {
      toast.error("Impossible de contacter le service IA");
    } finally {
      setIsCategorizing(false);
    }
  };

  // ─── Soumission ──────────────────────────────────────────
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!title.trim()) { toast.error("Le titre est requis"); return; }
    if (!amount || amountNum <= 0) { toast.error("Le montant doit être positif"); return; }
    if (!date) { toast.error("La date est requise"); return; }

    setIsSubmitting(true);
    try {
      const payload: Record<string, unknown> = {
        title: title.trim(),
        description: description.trim() || undefined,
        amount: amountNum,
        taxRate: taxRateNum,
        categoryId: categoryId || undefined,
        supplierId: supplierId || undefined,
        date,
        paymentMethod: paymentMethod || undefined,
        reference: reference.trim() || undefined,
        notes: notes.trim() || undefined,
      };

      const res = await fetch("/api/expenses", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });
      const json = await res.json();

      if (json.success) {
        toast.success("Dépense créée avec succès");
        router.push("/depenses");
      } else {
        toast.error(json.error ?? "Erreur lors de la création");
      }
    } catch {
      toast.error("Erreur réseau. Veuillez réessayer.");
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="max-w-2xl mx-auto p-6 space-y-6">
      {/* En-tête */}
      <div className="flex items-center gap-4">
        <Button variant="ghost" size="icon" onClick={() => router.back()}>
          <ArrowLeft className="h-4 w-4" />
        </Button>
        <div>
          <h1 className="text-2xl font-bold tracking-tight">Nouvelle dépense</h1>
          <p className="text-sm text-muted-foreground">Enregistrez une dépense professionnelle</p>
        </div>
      </div>

      <form onSubmit={handleSubmit} className="space-y-6">
        {/* Informations principales */}
        <Card>
          <CardHeader>
            <CardTitle className="text-base">Informations principales</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            {/* Titre */}
            <div className="space-y-1.5">
              <Label htmlFor="title">
                Titre <span className="text-destructive">*</span>
              </Label>
              <Input
                id="title"
                value={title}
                onChange={(e) => setTitle(e.target.value)}
                placeholder="Ex : Abonnement Slack Business"
                required
              />
            </div>

            {/* Description */}
            <div className="space-y-1.5">
              <Label htmlFor="description">Description</Label>
              <Textarea
                id="description"
                value={description}
                onChange={(e) => setDescription(e.target.value)}
                placeholder="Détails supplémentaires sur cette dépense..."
                rows={2}
              />
            </div>

            {/* Montant + TVA */}
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-1.5">
                <Label htmlFor="amount">
                  Montant HT (€) <span className="text-destructive">*</span>
                </Label>
                <Input
                  id="amount"
                  type="number"
                  min="0.01"
                  step="0.01"
                  value={amount}
                  onChange={(e) => setAmount(e.target.value)}
                  placeholder="0,00"
                  required
                />
              </div>
              <div className="space-y-1.5">
                <Label htmlFor="taxRate">Taux de TVA</Label>
                <Select value={taxRate} onValueChange={setTaxRate}>
                  <SelectTrigger id="taxRate">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {TAX_RATES.map((r) => (
                      <SelectItem key={r.value} value={r.value}>
                        {r.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>

            {/* Résumé TVA */}
            {amountNum > 0 && (
              <div className="flex items-center gap-4 text-sm bg-muted/50 rounded-lg px-3 py-2">
                <span className="text-muted-foreground">TVA :</span>
                <span className="font-medium">
                  {taxAmount.toLocaleString("fr-FR", { minimumFractionDigits: 2 })} €
                </span>
                <span className="text-muted-foreground ml-auto">Total TTC :</span>
                <span className="font-bold">
                  {totalTTC.toLocaleString("fr-FR", { minimumFractionDigits: 2 })} €
                </span>
              </div>
            )}
          </CardContent>
        </Card>

        {/* Catégorie + IA */}
        <Card>
          <CardHeader>
            <div className="flex items-center justify-between">
              <CardTitle className="text-base">Catégorie</CardTitle>
              <Button
                type="button"
                variant="outline"
                size="sm"
                onClick={handleCategorizeAI}
                disabled={isCategorizing || (!title && !description) || !amountNum}
                className="gap-2"
              >
                {isCategorizing ? (
                  <>
                    <Loader2 className="h-3.5 w-3.5 animate-spin" />
                    Analyse en cours...
                  </>
                ) : (
                  <>
                    <Sparkles className="h-3.5 w-3.5 text-purple-500" />
                    Catégoriser avec IA
                  </>
                )}
              </Button>
            </div>
          </CardHeader>
          <CardContent className="space-y-3">
            <Select value={categoryId} onValueChange={setCategoryId}>
              <SelectTrigger>
                <SelectValue placeholder="Sélectionner une catégorie..." />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="none">Sans catégorie</SelectItem>
                {categories.map((cat) => (
                  <SelectItem key={cat.id} value={cat.id}>
                    <span className="flex items-center gap-2">
                      <span
                        className="h-2.5 w-2.5 rounded-full shrink-0"
                        style={{ backgroundColor: cat.color }}
                      />
                      {cat.name}
                    </span>
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>

            {/* Résultat IA */}
            {aiResult && (
              <div className="flex items-start gap-3 rounded-lg border bg-purple-50 dark:bg-purple-950/20 p-3 text-sm">
                <Sparkles className="h-4 w-4 text-purple-500 mt-0.5 shrink-0" />
                <div className="space-y-1 flex-1">
                  <div className="flex items-center gap-2 flex-wrap">
                    <span className="font-medium">Suggestion IA :</span>
                    <Badge variant="secondary" className="text-xs">
                      {aiResult.categoryName}
                    </Badge>
                    <span className="text-muted-foreground text-xs">
                      {Math.round(aiResult.confidence * 100)}% de confiance
                    </span>
                  </div>
                  {aiResult.explanation && (
                    <p className="text-muted-foreground text-xs">{aiResult.explanation}</p>
                  )}
                </div>
                <button
                  type="button"
                  onClick={() => setAiResult(null)}
                  className="text-muted-foreground hover:text-foreground"
                >
                  <X className="h-3.5 w-3.5" />
                </button>
              </div>
            )}
          </CardContent>
        </Card>

        {/* Informations complémentaires */}
        <Card>
          <CardHeader>
            <CardTitle className="text-base">Informations complémentaires</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            {/* Fournisseur + Date */}
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-1.5">
                <Label htmlFor="date">
                  Date <span className="text-destructive">*</span>
                </Label>
                <Input
                  id="date"
                  type="date"
                  value={date}
                  onChange={(e) => setDate(e.target.value)}
                  required
                />
              </div>
              <div className="space-y-1.5">
                <Label htmlFor="paymentMethod">Méthode de paiement</Label>
                <Select value={paymentMethod} onValueChange={setPaymentMethod}>
                  <SelectTrigger id="paymentMethod">
                    <SelectValue placeholder="Choisir..." />
                  </SelectTrigger>
                  <SelectContent>
                    {PAYMENT_METHODS.map((m) => (
                      <SelectItem key={m.value} value={m.value}>
                        {m.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>

            {/* Référence */}
            <div className="space-y-1.5">
              <Label htmlFor="reference">Référence / N° facture fournisseur</Label>
              <Input
                id="reference"
                value={reference}
                onChange={(e) => setReference(e.target.value)}
                placeholder="Ex : INV-2024-0042"
              />
            </div>

            {/* Notes */}
            <div className="space-y-1.5">
              <Label htmlFor="notes">Notes internes</Label>
              <Textarea
                id="notes"
                value={notes}
                onChange={(e) => setNotes(e.target.value)}
                placeholder="Informations pour l'équipe comptable..."
                rows={2}
              />
            </div>
          </CardContent>
        </Card>

        {/* Justificatif */}
        <Card>
          <CardHeader>
            <CardTitle className="text-base">Justificatif</CardTitle>
          </CardHeader>
          <CardContent>
            {receipt ? (
              <div className="flex items-center gap-3 p-3 rounded-lg border bg-muted/30">
                <Upload className="h-4 w-4 text-muted-foreground shrink-0" />
                <span className="text-sm flex-1 truncate">{receipt.name}</span>
                <span className="text-xs text-muted-foreground">
                  {(receipt.size / 1024).toFixed(0)} Ko
                </span>
                <button
                  type="button"
                  onClick={() => setReceipt(null)}
                  className="text-muted-foreground hover:text-foreground ml-2"
                >
                  <X className="h-4 w-4" />
                </button>
              </div>
            ) : (
              <label className={cn(
                "flex flex-col items-center justify-center w-full h-24 border-2 border-dashed rounded-lg cursor-pointer",
                "text-muted-foreground hover:text-foreground hover:border-primary/50 transition-colors"
              )}>
                <Upload className="h-6 w-6 mb-1" />
                <span className="text-sm font-medium">Cliquer pour téléverser</span>
                <span className="text-xs">PDF, JPG, PNG — Max 10 Mo</span>
                <input
                  type="file"
                  className="hidden"
                  accept=".pdf,.jpg,.jpeg,.png,.webp"
                  onChange={(e) => {
                    const file = e.target.files?.[0];
                    if (file) {
                      if (file.size > 10 * 1024 * 1024) {
                        toast.error("Le fichier dépasse la limite de 10 Mo");
                        return;
                      }
                      setReceipt(file);
                    }
                  }}
                />
              </label>
            )}
          </CardContent>
        </Card>

        {/* Actions */}
        <div className="flex items-center gap-3 justify-end">
          <Button
            type="button"
            variant="outline"
            onClick={() => router.back()}
            disabled={isSubmitting}
          >
            Annuler
          </Button>
          <Button type="submit" disabled={isSubmitting} className="min-w-[140px]">
            {isSubmitting ? (
              <>
                <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                Enregistrement...
              </>
            ) : (
              "Enregistrer la dépense"
            )}
          </Button>
        </div>
      </form>
    </div>
  );
}
