"use client";

import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Card, CardContent } from "@/components/ui/card";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { createFacture } from "@/actions/factures";
import { formatMoney } from "@/lib/utils";
import { Loader2, FileText } from "lucide-react";

interface ReservationOption {
  id: string;
  label: string;
  prix_total: number;
}

interface Props {
  reservations: ReservationOption[];
  defaultReservationId?: string;
  devise: string;
  tauxTaxe: number;
}

export function GenerateFactureForm({
  reservations,
  defaultReservationId,
  devise,
  tauxTaxe,
}: Props) {
  const router = useRouter();
  const [pending, startTransition] = useTransition();
  const [reservationId, setReservationId] = useState(defaultReservationId || "");
  const [remise, setRemise] = useState(0);

  const reservation = reservations.find((r) => r.id === reservationId);
  const sousTotal = reservation ? reservation.prix_total - remise : 0;
  const taxe = (sousTotal * tauxTaxe) / 100;
  const total = sousTotal + taxe;

  function onSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    if (!reservationId) {
      toast.error("Sélectionnez une réservation");
      return;
    }
    startTransition(async () => {
      const result = await createFacture(reservationId, remise);
      if (result?.error) toast.error(result.error);
    });
  }

  return (
    <form onSubmit={onSubmit}>
      <Card>
        <CardContent className="p-6 space-y-4">
          <div className="space-y-2">
            <Label>Réservation *</Label>
            <Select value={reservationId} onValueChange={setReservationId}>
              <SelectTrigger>
                <SelectValue placeholder="Sélectionner..." />
              </SelectTrigger>
              <SelectContent>
                {reservations.length === 0 ? (
                  <SelectItem value="none" disabled>
                    Toutes les réservations ont déjà une facture
                  </SelectItem>
                ) : (
                  reservations.map((r) => (
                    <SelectItem key={r.id} value={r.id}>
                      {r.label} · {formatMoney(r.prix_total, devise)}
                    </SelectItem>
                  ))
                )}
              </SelectContent>
            </Select>
          </div>

          <div className="space-y-2">
            <Label htmlFor="remise">Remise (optionnel)</Label>
            <Input
              id="remise"
              type="number"
              min="0"
              step="0.01"
              value={remise}
              onChange={(e) => setRemise(Number(e.target.value) || 0)}
            />
          </div>

          {reservation && (
            <div className="bg-secondary/50 rounded-md p-4 space-y-2 text-sm">
              <div className="flex justify-between">
                <span>Sous-total</span>
                <span>{formatMoney(reservation.prix_total, devise)}</span>
              </div>
              {remise > 0 && (
                <div className="flex justify-between text-success">
                  <span>Remise</span>
                  <span>- {formatMoney(remise, devise)}</span>
                </div>
              )}
              <div className="flex justify-between">
                <span>Taxe ({tauxTaxe}%)</span>
                <span>{formatMoney(taxe, devise)}</span>
              </div>
              <div className="flex justify-between font-bold pt-2 border-t">
                <span>Total</span>
                <span className="text-accent">{formatMoney(total, devise)}</span>
              </div>
            </div>
          )}

          <div className="flex gap-2 justify-end pt-2 border-t">
            <Button
              type="button"
              variant="outline"
              onClick={() => router.back()}
              disabled={pending}
            >
              Annuler
            </Button>
            <Button type="submit" variant="accent" disabled={pending || !reservationId}>
              {pending ? <Loader2 className="w-4 h-4 animate-spin" /> : <FileText className="w-4 h-4" />}
              Générer la facture
            </Button>
          </div>
        </CardContent>
      </Card>
    </form>
  );
}
