
import React from 'react';
import { zodResolver } from '@hookform/resolvers/zod';
import { useForm } from 'react-hook-form';
import { Transaction } from '@/components/TransactionCard';
import { useBudget } from '@/contexts/BudgetContext';
import { 
  Dialog, 
  DialogContent, 
  DialogHeader, 
  DialogTitle, 
  DialogFooter,
  DialogClose
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Form } from '@/components/ui/form';
import { toast } from '@/components/ui/use-toast';
import TransactionFormFields, { 
  transactionFormSchema, 
  formatWithCommas,
  TransactionFormValues
} from './transaction/TransactionFormFields';
import TransactionDeleteAlert from './transaction/TransactionDeleteAlert';
import { useIsMobile } from '@/hooks/use-mobile';

interface TransactionEditDialogProps {
  transaction: Transaction;
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onSave?: (updatedTransaction: Transaction) => void;
  onDelete?: (id: string) => void;
}

const TransactionEditDialog: React.FC<TransactionEditDialogProps> = ({
  transaction,
  open,
  onOpenChange,
  onSave,
  onDelete
}) => {
  const { updateTransaction, deleteTransaction } = useBudget();
  const isMobile = useIsMobile();

  const form = useForm<TransactionFormValues>({
    resolver: zodResolver(transactionFormSchema),
    defaultValues: {
      title: transaction.title,
      amount: formatWithCommas(transaction.amount.toString()),
      category: transaction.category as '식비' | '생활비' | '교통비',
    },
  });

  const handleSubmit = (values: TransactionFormValues) => {
    // Remove commas from amount string and convert to number
    const cleanAmount = values.amount.replace(/,/g, '');
    
    const updatedTransaction = {
      ...transaction,
      title: values.title,
      amount: Number(cleanAmount),
      category: values.category,
    };
    
    // 컨텍스트를 통해 트랜잭션 업데이트
    updateTransaction(updatedTransaction);
    
    // 부모 컴포넌트의 onSave 콜백이 있다면 호출
    if (onSave) {
      onSave(updatedTransaction);
    }
    
    onOpenChange(false);
    
    toast({
      title: "지출이 수정되었습니다",
      description: `${values.title} 항목이 ${formatWithCommas(cleanAmount)}원으로 수정되었습니다.`,
    });
  };

  const handleDelete = () => {
    // 컨텍스트를 통해 트랜잭션 삭제
    deleteTransaction(transaction.id);
    
    // 부모 컴포넌트의 onDelete 콜백이 있다면 호출
    if (onDelete) {
      onDelete(transaction.id);
    }
    
    onOpenChange(false);
    
    toast({
      title: "지출이 삭제되었습니다",
      description: `${transaction.title} 항목이 삭제되었습니다.`,
    });
  };
  
  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className={`sm:max-w-md mx-auto ${isMobile ? 'rounded-xl overflow-hidden' : ''}`}>
        <DialogHeader>
          <DialogTitle>지출 수정</DialogTitle>
        </DialogHeader>
        
        <Form {...form}>
          <form onSubmit={form.handleSubmit(handleSubmit)} className="space-y-4">
            <TransactionFormFields form={form} />
            
            <DialogFooter className="flex justify-between gap-2 mt-6">
              <TransactionDeleteAlert onDelete={handleDelete} />
              <div className="flex gap-2">
                <DialogClose asChild>
                  <Button type="button" variant="outline">취소</Button>
                </DialogClose>
                <Button 
                  type="submit"
                  className="bg-neuro-income text-white hover:bg-neuro-income/90"
                >
                  저장
                </Button>
              </div>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  );
};

export default TransactionEditDialog;
