
import React, { useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import { Form, FormField, FormItem, FormLabel } from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Loader2, CreditCard, Banknote } from 'lucide-react';
import ExpenseCategorySelector from './ExpenseCategorySelector';
import { Badge } from '@/components/ui/badge';
import { getPersonalizedTitleSuggestions } from '@/utils/userTitlePreferences';
import { Separator } from '@/components/ui/separator';

export interface ExpenseFormValues {
  title: string;
  amount: string;
  category: string;
  paymentMethod: '신용카드' | '현금';
}

interface ExpenseFormProps {
  onSubmit: (data: ExpenseFormValues) => void;
  onCancel: () => void;
  isSubmitting?: boolean;
}

const ExpenseForm: React.FC<ExpenseFormProps> = ({ onSubmit, onCancel, isSubmitting = false }) => {
  const form = useForm<ExpenseFormValues>({
    defaultValues: {
      title: '',
      amount: '',
      category: '음식',
      paymentMethod: '신용카드'
    }
  });
  
  // 상태 관리 추가
  const [showTitleSuggestions, setShowTitleSuggestions] = useState(false);
  const [showPaymentMethod, setShowPaymentMethod] = useState(false);
  
  // 현재 선택된 카테고리 가져오기
  const selectedCategory = form.watch('category');
  const selectedPaymentMethod = form.watch('paymentMethod');
  
  // 선택된 카테고리에 대한 개인화된 제목 제안 목록 상태
  const [titleSuggestions, setTitleSuggestions] = useState<string[]>([]);
  
  // 카테고리가 변경될 때마다 개인화된 제목 목록 업데이트 및 제목 추천 표시
  useEffect(() => {
    if (selectedCategory) {
      const suggestions = getPersonalizedTitleSuggestions(selectedCategory);
      setTitleSuggestions(suggestions);
      // 약간의 지연 후 제목 추천 표시 (애니메이션을 위해)
      setTimeout(() => {
        setShowTitleSuggestions(true);
      }, 100);
    } else {
      setShowTitleSuggestions(false);
    }
  }, [selectedCategory]);
  
  // 제안된 제목 클릭 시 제목 필드에 설정
  const handleTitleSuggestionClick = (suggestion: string) => {
    form.setValue('title', suggestion);
  };
  
  // Format number with commas
  const formatWithCommas = (value: string): string => {
    // Remove commas first to avoid duplicates when typing
    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);
  };
  
  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
        {/* 카테고리 필드를 가장 먼저 배치 */}
        <FormField
          control={form.control}
          name="category"
          render={({ field }) => (
            <FormItem>
              <FormLabel>카테고리</FormLabel>
              <ExpenseCategorySelector 
                value={field.value} 
                onValueChange={(value) => field.onChange(value)}
              />
            </FormItem>
          )}
        />
        
        {/* 카테고리별 제목 제안 - 카테고리 선택 후에만 표시, 서랍처럼 열리는 애니메이션 적용 */}
        {selectedCategory && (
          <div 
            className={`overflow-hidden transition-all duration-300 ease-out ${
              showTitleSuggestions 
                ? 'max-h-24 opacity-100 translate-y-0' 
                : 'max-h-0 opacity-0 -translate-y-4'
            }`}
          >
            {titleSuggestions.length > 0 && (
              <div className="flex flex-wrap gap-2 mt-1 mb-2">
                {titleSuggestions.map((suggestion) => (
                  <Badge 
                    key={suggestion}
                    variant="outline"
                    className="cursor-pointer hover:bg-neuro-income/10 transition-colors px-3 py-1"
                    onClick={() => handleTitleSuggestionClick(suggestion)}
                  >
                    {suggestion}
                  </Badge>
                ))}
              </div>
            )}
          </div>
        )}
        
        {/* 제목 필드를 두 번째로 배치 */}
        <FormField
          control={form.control}
          name="title"
          render={({ field }) => (
            <FormItem>
              <FormLabel>제목</FormLabel>
              <Input 
                placeholder="지출 내역을 입력하세요" 
                {...field} 
                disabled={isSubmitting}
              />
            </FormItem>
          )}
        />
        
        {/* 금액 필드를 세 번째로 배치 */}
        <FormField
          control={form.control}
          name="amount"
          render={({ field }) => (
            <FormItem>
              <FormLabel>금액</FormLabel>
              <Input 
                placeholder="금액을 입력하세요" 
                value={field.value}
                onChange={handleAmountChange}
                onFocus={() => setShowPaymentMethod(true)}
                disabled={isSubmitting}
              />
            </FormItem>
          )}
        />
        
        {/* 지출 방법 필드는 금액 입력 시에만 표시 - 서랍처럼 열리는 애니메이션 적용 */}
        <div 
          className={`overflow-hidden transition-all duration-300 ease-out ${
            showPaymentMethod 
              ? 'max-h-36 opacity-100 translate-y-0' 
              : 'max-h-0 opacity-0 -translate-y-4'
          }`}
        >
          <Separator className="my-2" />
          
          <FormField
            control={form.control}
            name="paymentMethod"
            render={({ field }) => (
              <FormItem>
                <FormLabel>지출 방법</FormLabel>
                <div className="grid grid-cols-2 gap-3">
                  <div
                    className={`flex items-center justify-center gap-2 p-2 rounded-md cursor-pointer border transition-colors ${
                      field.value === '신용카드'
                        ? 'border-neuro-income bg-neuro-income/10'
                        : 'border-gray-200 hover:bg-gray-50'
                    } ${isSubmitting ? 'opacity-50 cursor-not-allowed' : ''}`}
                    onClick={() => !isSubmitting && form.setValue('paymentMethod', '신용카드')}
                  >
                    <CreditCard size={16} className="text-neuro-income" />
                    <span className="text-xs">신용카드</span>
                  </div>
                  <div
                    className={`flex items-center justify-center gap-2 p-2 rounded-md cursor-pointer border transition-colors ${
                      field.value === '현금'
                        ? 'border-neuro-income bg-neuro-income/10'
                        : 'border-gray-200 hover:bg-gray-50'
                    } ${isSubmitting ? 'opacity-50 cursor-not-allowed' : ''}`}
                    onClick={() => !isSubmitting && form.setValue('paymentMethod', '현금')}
                  >
                    <Banknote size={16} className="text-neuro-income" />
                    <span className="text-xs">현금</span>
                  </div>
                </div>
              </FormItem>
            )}
          />
        </div>
        
        <div className="flex justify-end gap-2 pt-2">
          <Button 
            type="button" 
            variant="outline" 
            onClick={onCancel}
            disabled={isSubmitting}
          >
            취소
          </Button>
          <Button 
            type="submit"
            className="bg-neuro-income text-white hover:bg-neuro-income/90"
            disabled={isSubmitting}
          >
            {isSubmitting ? (
              <>
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                저장 중...
              </>
            ) : '저장'}
          </Button>
        </div>
      </form>
    </Form>
  );
};

export default ExpenseForm;
