"use client";

import { useState } from "react";

import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { CreditCard, Loader2 } from "lucide-react";

import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import type { AccountType, CreateAccountRequest } from "@/types/banking";

const accountFormSchema = z.object({
  client_id: z.string().min(1, "Client requis"),
  account_name: z.string().min(3, "Le nom du compte doit contenir au moins 3 caractères"),
  account_type: z.enum(["savings", "checking", "credit", "pso", "loan"] as const),
  description: z.string().optional(),
  initial_balance: z.number().min(0, "Le solde initial doit être positif").default(0),
  credit_limit: z.number().min(0, "La limite de crédit doit être positive").optional(),
  interest_rate: z
    .number()
    .min(0, "Le taux d'intérêt doit être positif")
    .max(100, "Le taux ne peut pas dépasser 100%")
    .optional(),
  overdraft_limit: z.number().min(0, "La limite de découvert doit être positive").optional(),
  is_joint_account: z.boolean().default(false),
  auto_calculate_interest: z.boolean().default(true),
  status: z.enum(["active", "inactive", "frozen", "closed"] as const).default("active"),
});

type AccountFormValues = z.infer<typeof accountFormSchema>;

interface AccountFormProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  mode: "create" | "edit";
  accountId?: string;
  initialData?: Partial<AccountFormValues>;
  clients?: Array<{ id: string; name: string; email: string }>;
  onSubmit: (data: CreateAccountRequest) => Promise<void>;
  loading?: boolean;
}

const accountTypes = [
  { value: "savings", label: "Épargne", description: "Compte d'épargne traditionnel" },
  { value: "checking", label: "Courant", description: "Compte courant pour opérations quotidiennes" },
  { value: "credit", label: "Crédit", description: "Ligne de crédit" },
  { value: "pso", label: "Parts Sociales", description: "Compte des parts sociales" },
  { value: "loan", label: "Prêt", description: "Compte de prêt" },
];

const statusOptions = [
  { value: "active", label: "Actif" },
  { value: "inactive", label: "Inactif" },
  { value: "frozen", label: "Gelé" },
  { value: "closed", label: "Fermé" },
];

export function AccountForm({
  open,
  onOpenChange,
  mode,
  initialData,
  clients = [],
  onSubmit,
  loading = false,
}: Readonly<AccountFormProps>) {
  const form = useForm<AccountFormValues>({
    resolver: zodResolver(accountFormSchema),
    defaultValues: {
      client_id: "",
      account_name: "",
      account_type: "savings",
      description: "",
      initial_balance: 0,
      credit_limit: undefined,
      interest_rate: 2.5,
      overdraft_limit: undefined,
      is_joint_account: false,
      auto_calculate_interest: true,
      status: "active",
      ...initialData,
    },
  });

  const watchedAccountType = form.watch("account_type");

  const handleSubmit = async (data: AccountFormValues) => {
    try {
      const submitData: CreateAccountRequest = {
        client_id: parseInt(data.client_id),
        account_type: data.account_type,
        currency: "XOF", // Default currency for COOP-CA AMIFOND
        // Convert numbers to strings for API
        overdraft_limit: data.overdraft_limit ? data.overdraft_limit.toString() : undefined,
        interest_rate: data.interest_rate ? data.interest_rate.toString() : undefined,
        notes: data.description,
      };

      await onSubmit(submitData);
      form.reset();
      onOpenChange(false);
    } catch (error) {
      console.error("Erreur lors de la soumission:", error);
    }
  };

  const isEditing = mode === "edit";
  const showCreditFields = watchedAccountType === "credit";
  const showOverdraftFields = ["checking", "savings"].includes(watchedAccountType);
  const showInterestFields = ["savings", "credit", "loan"].includes(watchedAccountType);

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-h-[90vh] max-w-2xl overflow-y-auto">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <CreditCard className="h-5 w-5" />
            {isEditing ? "Modifier le compte" : "Créer un nouveau compte"}
          </DialogTitle>
          <DialogDescription>
            {isEditing
              ? "Modifiez les informations du compte bancaire."
              : "Créez un nouveau compte bancaire pour le client sélectionné."}
          </DialogDescription>
        </DialogHeader>

        <Form {...form}>
          <form onSubmit={form.handleSubmit(handleSubmit)} className="space-y-6">
            {/* Sélection du client */}
            <FormField
              control={form.control}
              name="client_id"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Client *</FormLabel>
                  <Select onValueChange={field.onChange} defaultValue={field.value}>
                    <FormControl>
                      <SelectTrigger>
                        <SelectValue placeholder="Sélectionner un client" />
                      </SelectTrigger>
                    </FormControl>
                    <SelectContent>
                      {clients.map((client) => (
                        <SelectItem key={client.id} value={client.id}>
                          <div className="flex flex-col">
                            <span className="font-medium">{client.name}</span>
                            <span className="text-muted-foreground text-xs">{client.email}</span>
                          </div>
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  <FormMessage />
                </FormItem>
              )}
            />

            {/* Informations de base */}
            <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
              <FormField
                control={form.control}
                name="account_name"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Nom du compte *</FormLabel>
                    <FormControl>
                      <Input placeholder="Ex: Compte Épargne Principal" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="account_type"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Type de compte *</FormLabel>
                    <Select onValueChange={field.onChange} defaultValue={field.value}>
                      <FormControl>
                        <SelectTrigger>
                          <SelectValue placeholder="Type de compte" />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        {accountTypes.map((type) => (
                          <SelectItem key={type.value} value={type.value}>
                            <div className="flex flex-col">
                              <span className="font-medium">{type.label}</span>
                              <span className="text-muted-foreground text-xs">{type.description}</span>
                            </div>
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            {/* Description */}
            <FormField
              control={form.control}
              name="description"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Description</FormLabel>
                  <FormControl>
                    <Textarea placeholder="Description du compte..." {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            {/* Paramètres financiers */}
            <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
              <FormField
                control={form.control}
                name="initial_balance"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Solde initial</FormLabel>
                    <FormControl>
                      <Input
                        type="number"
                        min="0"
                        step="0.01"
                        placeholder="0.00"
                        {...field}
                        onChange={(e) => field.onChange(Number(e.target.value))}
                      />
                    </FormControl>
                    <FormDescription>Montant initial du compte</FormDescription>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {showInterestFields && (
                <FormField
                  control={form.control}
                  name="interest_rate"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Taux d&apos;intérêt (%)</FormLabel>
                      <FormControl>
                        <Input
                          type="number"
                          min="0"
                          max="100"
                          step="0.01"
                          placeholder="2.50"
                          {...field}
                          onChange={(e) => field.onChange(Number(e.target.value))}
                        />
                      </FormControl>
                      <FormDescription>Taux d&apos;intérêt annuel</FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              )}
            </div>

            {/* Limites spécifiques */}
            {(showCreditFields || showOverdraftFields) && (
              <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                {showCreditFields && (
                  <FormField
                    control={form.control}
                    name="credit_limit"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Limite de crédit</FormLabel>
                        <FormControl>
                          <Input
                            type="number"
                            min="0"
                            step="0.01"
                            placeholder="10000.00"
                            {...field}
                            onChange={(e) => field.onChange(Number(e.target.value))}
                          />
                        </FormControl>
                        <FormDescription>Limite maximale de crédit autorisée</FormDescription>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                )}

                {showOverdraftFields && (
                  <FormField
                    control={form.control}
                    name="overdraft_limit"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Limite de découvert</FormLabel>
                        <FormControl>
                          <Input
                            type="number"
                            min="0"
                            step="0.01"
                            placeholder="500.00"
                            {...field}
                            onChange={(e) => field.onChange(Number(e.target.value))}
                          />
                        </FormControl>
                        <FormDescription>Découvert autorisé</FormDescription>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                )}
              </div>
            )}

            {/* Options avancées */}
            <div className="space-y-4">
              <FormField
                control={form.control}
                name="is_joint_account"
                render={({ field }) => (
                  <FormItem className="flex flex-row items-start space-y-0 space-x-3">
                    <FormControl>
                      <Checkbox checked={field.value} onCheckedChange={field.onChange} />
                    </FormControl>
                    <div className="space-y-1 leading-none">
                      <FormLabel>Compte joint</FormLabel>
                      <FormDescription>Ce compte est partagé entre plusieurs titulaires</FormDescription>
                    </div>
                  </FormItem>
                )}
              />

              {showInterestFields && (
                <FormField
                  control={form.control}
                  name="auto_calculate_interest"
                  render={({ field }) => (
                    <FormItem className="flex flex-row items-start space-y-0 space-x-3">
                      <FormControl>
                        <Checkbox checked={field.value} onCheckedChange={field.onChange} />
                      </FormControl>
                      <div className="space-y-1 leading-none">
                        <FormLabel>Calcul automatique des intérêts</FormLabel>
                        <FormDescription>Les intérêts seront calculés automatiquement</FormDescription>
                      </div>
                    </FormItem>
                  )}
                />
              )}
            </div>

            {/* Statut */}
            <FormField
              control={form.control}
              name="status"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Statut du compte</FormLabel>
                  <Select onValueChange={field.onChange} defaultValue={field.value}>
                    <FormControl>
                      <SelectTrigger>
                        <SelectValue placeholder="Statut" />
                      </SelectTrigger>
                    </FormControl>
                    <SelectContent>
                      {statusOptions.map((status) => (
                        <SelectItem key={status.value} value={status.value}>
                          {status.label}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  <FormMessage />
                </FormItem>
              )}
            />

            <DialogFooter>
              <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
                Annuler
              </Button>
              <Button type="submit" disabled={loading}>
                {loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                {isEditing ? "Modifier" : "Créer"} le compte
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  );
}
