import React, { useState, useEffect } from 'react';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Check, ChevronDown, ChevronUp, Wallet } from 'lucide-react';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
import { markBudgetAsModified } from '@/utils/sync/budget/modifiedBudgetsTracker';

interface BudgetGoalProps {
  initialBudgets: {
    daily: number;
    weekly: number;
    monthly: number;
  };
  onSave: (type: 'daily' | 'weekly' | 'monthly', amount: number) => void;
  highlight?: boolean;
}

const BudgetInputCard: React.FC<BudgetGoalProps> = ({
  initialBudgets,
  onSave,
  highlight = false
}) => {
  const [selectedTab, setSelectedTab] = useState<'daily' | 'weekly' | 'monthly'>('daily');
  const [budgetInputs, setBudgetInputs] = useState({
    daily: initialBudgets.daily > 0 ? initialBudgets.daily.toString() : '',
    weekly: initialBudgets.weekly > 0 ? initialBudgets.weekly.toString() : '',
    monthly: initialBudgets.monthly > 0 ? initialBudgets.monthly.toString() : ''
  });
  const [isOpen, setIsOpen] = useState(highlight);

  // Format with commas for display
  const formatWithCommas = (amount: string) => {
    // Remove commas first to handle re-formatting
    const numericValue = amount.replace(/,/g, '');
    return numericValue.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  };

  // 초기값 변경시 입력 필드 값 업데이트
  useEffect(() => {
    setBudgetInputs({
      daily: initialBudgets.daily > 0 ? initialBudgets.daily.toString() : '',
      weekly: initialBudgets.weekly > 0 ? initialBudgets.weekly.toString() : '',
      monthly: initialBudgets.monthly > 0 ? initialBudgets.monthly.toString() : ''
    });
  }, [initialBudgets]);

  const handleInputChange = (value: string, type: 'daily' | 'weekly' | 'monthly') => {
    // Remove all non-numeric characters
    const numericValue = value.replace(/[^0-9]/g, '');
    setBudgetInputs(prev => ({
      ...prev,
      [type]: numericValue
    }));
  };

  const handleSave = () => {
    const amount = parseInt(budgetInputs[selectedTab].replace(/,/g, ''), 10) || 0;
    if (amount <= 0) {
      return; // 0 이하의 금액은 저장하지 않음
    }
    
    // 즉시 입력 필드를 업데이트하여 사용자에게 피드백 제공
    setBudgetInputs(prev => ({
      ...prev,
      [selectedTab]: amount.toString()
    }));
    
    // 즉시 콜랩시블을 닫아 사용자에게 완료 피드백 제공
    setIsOpen(false);
    
    // 월간 예산 변경 시 수정 추적 시스템에 기록
    if (selectedTab === 'monthly') {
      try {
        markBudgetAsModified(amount);
        console.log(`[예산 추적] 월간 예산 변경 추적: ${amount}원`);
      } catch (error) {
        console.error('[예산 추적] 예산 변경 추적 실패:', error);
      }
    }
    
    // 예산 저장
    onSave(selectedTab, amount);
  };

  // 비어있으면 빈 문자열을, 그렇지 않으면 포맷팅된 문자열을 반환
  const getDisplayValue = (type: 'daily' | 'weekly' | 'monthly') => {
    return budgetInputs[type] === '' ? '' : formatWithCommas(budgetInputs[type]);
  };

  // 금액을 표시할 때 0원이면 '설정되지 않음'으로 표시
  const getGoalDisplayText = (type: 'daily' | 'weekly' | 'monthly') => {
    const amount = parseInt(budgetInputs[type].replace(/,/g, ''), 10) || 0;
    if (amount === 0) return '설정되지 않음';
    return formatWithCommas(budgetInputs[type]) + '원';
  };

  return (
    <Collapsible 
      open={isOpen} 
      onOpenChange={setIsOpen}
      className={`neuro-card ${highlight ? 'border-2 border-neuro-income shadow-lg' : ''}`}
    >
      <CollapsibleTrigger className="flex items-center justify-between w-full p-4">
        <span className={`text-sm font-medium flex items-center ${highlight ? 'text-neuro-income' : ''}`}>
          {highlight && <Wallet size={18} className="mr-2 animate-pulse" />}
          예산 목표 설정하기
        </span>
        {isOpen ? (
          <ChevronUp size={18} className="text-gray-500" />
        ) : (
          <ChevronDown size={18} className="text-gray-500" />
        )}
      </CollapsibleTrigger>
      
      <CollapsibleContent className="px-4 pb-4">
        <Tabs defaultValue="daily" value={selectedTab} onValueChange={value => setSelectedTab(value as 'daily' | 'weekly' | 'monthly')} className="w-full">
          <TabsList className="grid grid-cols-3 mb-4 bg-transparent">
            <TabsTrigger value="daily" className="data-[state=active]:shadow-neuro-pressed data-[state=active]:bg-transparent">일일 예산</TabsTrigger>
            <TabsTrigger value="weekly" className="data-[state=active]:shadow-neuro-pressed data-[state=active]:bg-transparent">주간 예산</TabsTrigger>
            <TabsTrigger value="monthly" className="data-[state=active]:shadow-neuro-pressed data-[state=active]:bg-transparent">월간 예산</TabsTrigger>
          </TabsList>

          <TabsContent value="daily" className="space-y-4 mt-0">
            <div className="flex items-center space-x-2">
              <Input 
                value={getDisplayValue('daily')}
                onChange={e => handleInputChange(e.target.value, 'daily')} 
                placeholder="목표 금액 입력" 
                className="neuro-pressed" 
              />
              <Button onClick={handleSave} size="icon" className={`neuro-flat ${highlight ? 'bg-neuro-income hover:bg-neuro-income/90' : 'bg-slate-400 hover:bg-slate-300'} text-white`}>
                <Check size={18} />
              </Button>
            </div>
            <p className="text-xs text-gray-500">
              현재 일일 목표: {getGoalDisplayText('daily')}
            </p>
          </TabsContent>

          <TabsContent value="weekly" className="space-y-4 mt-0">
            <div className="flex items-center space-x-2">
              <Input 
                value={getDisplayValue('weekly')}
                onChange={e => handleInputChange(e.target.value, 'weekly')} 
                placeholder="목표 금액 입력" 
                className="neuro-pressed" 
              />
              <Button onClick={handleSave} size="icon" className={`neuro-flat ${highlight ? 'bg-neuro-income hover:bg-neuro-income/90' : 'bg-slate-400 hover:bg-slate-300'} text-white`}>
                <Check size={18} />
              </Button>
            </div>
            <p className="text-xs text-gray-500">
              현재 주간 목표: {getGoalDisplayText('weekly')}
            </p>
          </TabsContent>

          <TabsContent value="monthly" className="space-y-4 mt-0">
            <div className="flex items-center space-x-2">
              <Input 
                value={getDisplayValue('monthly')}
                onChange={e => handleInputChange(e.target.value, 'monthly')} 
                placeholder="목표 금액 입력" 
                className="neuro-pressed" 
              />
              <Button onClick={handleSave} size="icon" className={`neuro-flat ${highlight ? 'bg-neuro-income hover:bg-neuro-income/90' : 'bg-slate-400 hover:bg-slate-300'} text-white`}>
                <Check size={18} />
              </Button>
            </div>
            <p className="text-xs text-gray-500">
              현재 월간 목표: {getGoalDisplayText('monthly')}
            </p>
          </TabsContent>
        </Tabs>
      </CollapsibleContent>
    </Collapsible>
  );
};

export default BudgetInputCard;
