import { useState, useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
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 {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form';
import { Save } from 'lucide-react';
import { CreateTreasuryEntryDTO } from '@/types/treasury';
import { treasuryService } from '@/services/treasuryService';
import { CashAccountDTO } from '@/types/treasury';
import { toast } from 'sonner';

interface TreasuryEntryFormModalProps {
  open: boolean;
  onClose: () => void;
  onSuccess: () => void;
}

const TREASURY_ENTRY_TYPES = [
  { value: 'PAYMENT_AUTHORIZATION', label: 'Autorização de Pagamento' },
  { value: 'PAYMENT_EXECUTION', label: 'Execução de Pagamento' },
  { value: 'CASH_DEPOSIT', label: 'Depósito em Caixa' },
  { value: 'CASH_WITHDRAWAL', label: 'Saque de Caixa' },
  { value: 'TRANSFER_IN', label: 'Transferência Recebida' },
  { value: 'TRANSFER_OUT', label: 'Transferência Enviada' },
  { value: 'BUDGET_ALLOCATION', label: 'Alocação Orçamentária' },
  { value: 'RECONCILIATION', label: 'Conciliação Bancária' },
] as const;

const formSchema = z.object({
  cashAccountId: z.string().min(1, 'Selecione uma conta de caixa'),
  type: z.enum([
    'PAYMENT_AUTHORIZATION',
    'PAYMENT_EXECUTION',
    'CASH_DEPOSIT',
    'CASH_WITHDRAWAL',
    'TRANSFER_IN',
    'TRANSFER_OUT',
    'BUDGET_ALLOCATION',
    'RECONCILIATION',
  ]),
  amount: z.string().min(1, 'Valor é obrigatório').refine(
    (val) => {
      const num = parseFloat(val);
      return !isNaN(num) && num > 0;
    },
    { message: 'Informe um valor válido maior que zero' }
  ),
  transactionDate: z.string().min(1, 'Data da transação é obrigatória'),
  documentReference: z.string().min(1, 'Referência do documento é obrigatória'),
  description: z.string().optional(),
});

type FormValues = z.infer<typeof formSchema>;

export function TreasuryEntryFormModal({
  open,
  onClose,
  onSuccess,
}: TreasuryEntryFormModalProps) {
  const [cashAccounts, setCashAccounts] = useState<CashAccountDTO[]>([]);

  const form = useForm<FormValues>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      cashAccountId: '',
      type: 'PAYMENT_AUTHORIZATION',
      amount: '',
      transactionDate: new Date().toISOString().split('T')[0],
      documentReference: '',
      description: '',
    },
  });

  useEffect(() => {
    if (open) {
      loadCashAccounts();
      form.reset({
        cashAccountId: '',
        type: 'PAYMENT_AUTHORIZATION',
        amount: '',
        transactionDate: new Date().toISOString().split('T')[0],
        documentReference: '',
        description: '',
      });
    }
  }, [open]);

  const loadCashAccounts = async () => {
    try {
      const accounts = await treasuryService.getCashAccounts({ activeOnly: true });
      setCashAccounts(accounts);
    } catch (error) {
      toast.error('Erro ao carregar contas de caixa');
    }
  };

  const onSubmit = async (data: FormValues) => {
    try {
      const dto: CreateTreasuryEntryDTO = {
        type: data.type,
        amount: parseFloat(data.amount),
        transactionDate: data.transactionDate,
        documentReference: data.documentReference,
        description: data.description || undefined,
        cashAccountId: data.cashAccountId,
        status: 'DRAFT',
      };

      await treasuryService.createTreasuryEntry(dto);
      toast.success('Entrada de tesouraria registrada com sucesso');
      onSuccess();
      onClose();
    } catch (error: any) {
      toast.error(error.message || 'Erro ao registrar entrada de tesouraria');
    }
  };

  return (
    <Dialog open={open} onOpenChange={onClose}>
      <DialogContent className="max-w-lg">
        <DialogHeader>
          <DialogTitle>Nova Entrada de Tesouraria</DialogTitle>
          <DialogDescription>
            Registre uma nova movimentação de tesouraria
          </DialogDescription>
        </DialogHeader>

        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
            <FormField
              control={form.control}
              name="cashAccountId"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Conta de Caixa *</FormLabel>
                  <Select onValueChange={field.onChange} defaultValue={field.value}>
                    <FormControl>
                      <SelectTrigger>
                        <SelectValue placeholder="Selecione a conta" />
                      </SelectTrigger>
                    </FormControl>
                    <SelectContent>
                      {cashAccounts.map((account) => (
                        <SelectItem key={account.id} value={account.id}>
                          {account.code} - {account.name}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="type"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Tipo de Entrada *</FormLabel>
                  <Select onValueChange={field.onChange} defaultValue={field.value}>
                    <FormControl>
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                    </FormControl>
                    <SelectContent>
                      {TREASURY_ENTRY_TYPES.map((entryType) => (
                        <SelectItem key={entryType.value} value={entryType.value}>
                          {entryType.label}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="amount"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Valor (XOF) *</FormLabel>
                  <FormControl>
                    <div className="relative">
                      <span className="absolute left-3 top-2.5 text-gray-400 font-medium text-sm">XOF</span>
                      <Input
                        type="number"
                        step="0.01"
                        min="0.01"
                        placeholder="0,00"
                        className="pl-12 font-mono text-lg"
                        {...field}
                      />
                    </div>
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="transactionDate"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Data da Transação *</FormLabel>
                  <FormControl>
                    <Input type="date" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="documentReference"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Referência do Documento *</FormLabel>
                  <FormControl>
                    <Input placeholder="Ex: DOC-2024-001" {...field} />
                  </FormControl>
                  <p className="text-xs text-muted-foreground">Obrigatório para fins de auditoria.</p>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="description"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Descrição</FormLabel>
                  <FormControl>
                    <Textarea
                      rows={3}
                      placeholder="Detalhes adicionais sobre a movimentação..."
                      className="resize-none"
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <DialogFooter>
              <Button type="button" variant="outline" onClick={onClose} disabled={form.formState.isSubmitting}>
                Cancelar
              </Button>
              <Button type="submit" disabled={form.formState.isSubmitting} className="gap-2">
                <Save className="w-4 h-4" />
                {form.formState.isSubmitting ? 'Salvando...' : 'Salvar Entrada'}
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  );
}
