
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 } from 'lucide-react';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';

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

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

  // 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.toString(),
      weekly: initialBudgets.weekly.toString(),
      monthly: 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;
    onSave(selectedTab, amount);
    // Close the collapsible after saving
    setIsOpen(false);
  };

  return (
    <Collapsible 
      open={isOpen} 
      onOpenChange={setIsOpen}
      className="neuro-card"
    >
      <CollapsibleTrigger className="flex items-center justify-between w-full p-4">
        <span className="text-sm font-medium">예산 목표 설정하기</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={formatWithCommas(budgetInputs.daily)} 
                onChange={e => handleInputChange(e.target.value, 'daily')} 
                placeholder="목표 금액 입력" 
                className="neuro-pressed" 
              />
              <Button onClick={handleSave} size="icon" className="neuro-flat text-slate-50 bg-slate-400 hover:bg-slate-300">
                <Check size={18} />
              </Button>
            </div>
            <p className="text-xs text-gray-500">현재 일일 목표: {formatWithCommas(budgetInputs.daily)}원</p>
          </TabsContent>

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

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

export default BudgetInputCard;
