
import React from 'react';
import { zodResolver } from '@hookform/resolvers/zod';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
import { Transaction } from '@/components/TransactionCard';
import { 
  Dialog, 
  DialogContent, 
  DialogHeader, 
  DialogTitle, 
  DialogFooter,
  DialogClose
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form';
import { Coffee, Home, Car } from 'lucide-react';

// Form schema for validation
const formSchema = z.object({
  title: z.string().min(1, '제목을 입력해주세요'),
  amount: z.string().min(1, '금액을 입력해주세요'),
  category: z.enum(['식비', '생활비', '교통비']),
});

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

const TransactionEditDialog: React.FC<TransactionEditDialogProps> = ({
  transaction,
  open,
  onOpenChange,
  onSave
}) => {
  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      title: transaction.title,
      amount: formatWithCommas(transaction.amount.toString()),
      category: transaction.category as any,
    },
  });

  const handleSubmit = (values: z.infer<typeof formSchema>) => {
    // Remove commas from amount string and convert to number
    const cleanAmount = values.amount.replace(/,/g, '');
    
    onSave({
      ...transaction,
      title: values.title,
      amount: Number(cleanAmount),
      category: values.category,
    });
    
    onOpenChange(false);
  };

  // Function to format number with commas
  const formatWithCommas = (value: string) => {
    const numericValue = value.replace(/[^0-9]/g, '');
    return numericValue.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  };

  const handleAmountChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const formattedValue = formatWithCommas(e.target.value);
    form.setValue('amount', formattedValue);
  };

  const categoryIcons: Record<string, React.ReactNode> = {
    식비: <Coffee size={18} />,
    생활비: <Home size={18} />,
    교통비: <Car size={18} />,
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>지출 수정</DialogTitle>
        </DialogHeader>
        
        <Form {...form}>
          <form onSubmit={form.handleSubmit(handleSubmit)} className="space-y-4">
            <FormField
              control={form.control}
              name="title"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>제목</FormLabel>
                  <FormControl>
                    <Input placeholder="제목을 입력하세요" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            
            <FormField
              control={form.control}
              name="amount"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>금액</FormLabel>
                  <FormControl>
                    <Input 
                      placeholder="금액을 입력하세요" 
                      {...field} 
                      onChange={handleAmountChange}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            
            <FormField
              control={form.control}
              name="category"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>카테고리</FormLabel>
                  <div className="grid grid-cols-3 gap-2">
                    {['식비', '생활비', '교통비'].map((category) => (
                      <div
                        key={category}
                        className={`flex items-center gap-2 p-2 rounded-md cursor-pointer border ${
                          field.value === category 
                            ? 'border-neuro-income bg-neuro-income/10' 
                            : 'border-gray-200'
                        }`}
                        onClick={() => form.setValue('category', category as any)}
                      >
                        <div className="p-1 rounded-full">
                          {categoryIcons[category]}
                        </div>
                        <span>{category}</span>
                      </div>
                    ))}
                  </div>
                  <FormMessage />
                </FormItem>
              )}
            />
            
            <DialogFooter className="sm:justify-between">
              <DialogClose asChild>
                <Button type="button" variant="outline">취소</Button>
              </DialogClose>
              <Button type="submit">저장</Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  );
};

export default TransactionEditDialog;
