import React, { useState } from 'react';
import NavBar from '@/components/NavBar';
import BudgetCard from '@/components/BudgetCard';
import BudgetInputCard from '@/components/BudgetInputCard';
import TransactionCard, { Transaction } from '@/components/TransactionCard';
import AddTransactionButton from '@/components/AddTransactionButton';
import { Wallet, TrendingUp, Bell } from 'lucide-react';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { toast } from '@/components/ui/use-toast';
const Index = () => {
  const [selectedTab, setSelectedTab] = useState("daily");

  // Sample data - in a real app, this would come from a data source
  const transactions: Transaction[] = [{
    id: '1',
    title: '식료품 구매',
    amount: 25000,
    date: '오늘, 12:30 PM',
    category: 'shopping',
    type: 'expense'
  }, {
    id: '2',
    title: '주유소',
    amount: 50000,
    date: '어제, 3:45 PM',
    category: 'transportation',
    type: 'expense'
  }, {
    id: '3',
    title: '월급',
    amount: 2500000,
    date: '2일전, 9:00 AM',
    category: 'income',
    type: 'income'
  }];

  // 예산 데이터 - 실제 앱에서는 백엔드에서 가져와야 함
  const [budgetData, setBudgetData] = useState({
    daily: {
      targetAmount: 30000,
      spentAmount: 15000,
      remainingAmount: 15000
    },
    weekly: {
      targetAmount: 200000,
      spentAmount: 120000,
      remainingAmount: 80000
    },
    monthly: {
      targetAmount: 1200000,
      spentAmount: 750000,
      remainingAmount: 450000
    }
  });
  const formatCurrency = (amount: number) => {
    return new Intl.NumberFormat('ko-KR', {
      style: 'currency',
      currency: 'KRW',
      maximumFractionDigits: 0
    }).format(amount);
  };

  // 퍼센트 계산 함수
  const calculatePercentage = (spent: number, target: number) => {
    return Math.min(Math.round(spent / target * 100), 100);
  };

  // 예산 목표 업데이트 함수
  const handleBudgetGoalUpdate = (type: 'daily' | 'weekly' | 'monthly', amount: number) => {
    setBudgetData(prev => {
      const remainingAmount = Math.max(0, amount - prev[type].spentAmount);
      return {
        ...prev,
        [type]: {
          ...prev[type],
          targetAmount: amount,
          remainingAmount: remainingAmount
        }
      };
    });
    toast({
      title: "목표 업데이트 완료",
      description: `${type === 'daily' ? '일일' : type === 'weekly' ? '주간' : '월간'} 목표가 ${amount.toLocaleString()}원으로 설정되었습니다.`
    });
  };
  return <div className="min-h-screen bg-neuro-background pb-24">
      <div className="max-w-md mx-auto px-6">
        {/* Header */}
        <header className="py-8">
          <div className="flex justify-between items-center">
            <div>
              <h1 className="text-2xl font-bold neuro-text">반갑습니다</h1>
              <p className="text-gray-500">적자 탈출 계획</p>
            </div>
            <button className="neuro-flat p-2.5 rounded-full">
              <Bell size={20} className="text-gray-600" />
            </button>
          </div>
        </header>

        {/* 목표 진행 상황 - 제목을 카드 위로 이동 */}
        <h2 className="text-lg font-semibold mb-3">목표 진행 상황</h2>
        <div className="neuro-card mb-6 overflow-hidden">
          <Tabs defaultValue="daily" value={selectedTab} onValueChange={setSelectedTab} 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>
            
            {/* 지출액 / 목표액 라벨 추가 */}
            <div className="text-sm text-gray-600 mb-2 px-1">지출액 / 목표액</div>

            <TabsContent value="daily" className="space-y-4 mt-0">
              <div className="space-y-4">
                <div>
                  <div className="flex items-center justify-between mb-2">
                    <p className="text-lg font-semibold">{formatCurrency(budgetData.daily.spentAmount)}</p>
                    <p className="text-sm text-gray-500">/ {formatCurrency(budgetData.daily.targetAmount)}</p>
                  </div>
                  
                  <div className="relative h-3 neuro-pressed overflow-hidden mt-2">
                    <div style={{
                    width: `${calculatePercentage(budgetData.daily.spentAmount, budgetData.daily.targetAmount)}%`
                  }} className="absolute top-0 left-0 h-full transition-all duration-700 ease-out bg-neuro-income" />
                  </div>
                  
                  <div className="mt-2 flex justify-end">
                    <span className={`text-xs font-medium ${calculatePercentage(budgetData.daily.spentAmount, budgetData.daily.targetAmount) >= 90 ? "text-neuro-expense" : "text-gray-500"}`}>
                      {calculatePercentage(budgetData.daily.spentAmount, budgetData.daily.targetAmount)}%
                    </span>
                  </div>
                </div>
                
                <div className="flex justify-between items-center pt-2 border-t border-gray-100">
                  <span className="text-gray-500 text-sm">지출 가능 금액</span>
                  <span className="font-semibold text-neuro-income">{formatCurrency(budgetData.daily.remainingAmount)}</span>
                </div>
              </div>
            </TabsContent>

            <TabsContent value="weekly" className="space-y-4 mt-0">
              <div className="space-y-4">
                <div>
                  <div className="flex items-center justify-between mb-2">
                    <p className="text-lg font-semibold">{formatCurrency(budgetData.weekly.spentAmount)}</p>
                    <p className="text-sm text-gray-500">/ {formatCurrency(budgetData.weekly.targetAmount)}</p>
                  </div>
                  
                  <div className="relative h-3 neuro-pressed overflow-hidden mt-2">
                    <div style={{
                    width: `${calculatePercentage(budgetData.weekly.spentAmount, budgetData.weekly.targetAmount)}%`
                  }} className="absolute top-0 left-0 h-full transition-all duration-700 ease-out bg-neuro-income" />
                  </div>
                  
                  <div className="mt-2 flex justify-end">
                    <span className={`text-xs font-medium ${calculatePercentage(budgetData.weekly.spentAmount, budgetData.weekly.targetAmount) >= 90 ? "text-neuro-expense" : "text-gray-500"}`}>
                      {calculatePercentage(budgetData.weekly.spentAmount, budgetData.weekly.targetAmount)}%
                    </span>
                  </div>
                </div>
                
                <div className="flex justify-between items-center pt-2 border-t border-gray-100">
                  <span className="text-gray-500 text-sm">지출 가능 금액</span>
                  <span className="font-semibold text-neuro-income">{formatCurrency(budgetData.weekly.remainingAmount)}</span>
                </div>
              </div>
            </TabsContent>

            <TabsContent value="monthly" className="space-y-4 mt-0">
              <div className="space-y-4">
                <div>
                  <div className="flex items-center justify-between mb-2">
                    <p className="text-lg font-semibold">{formatCurrency(budgetData.monthly.spentAmount)}</p>
                    <p className="text-sm text-gray-500">/ {formatCurrency(budgetData.monthly.targetAmount)}</p>
                  </div>
                  
                  <div className="relative h-3 neuro-pressed overflow-hidden mt-2">
                    <div style={{
                    width: `${calculatePercentage(budgetData.monthly.spentAmount, budgetData.monthly.targetAmount)}%`
                  }} className="absolute top-0 left-0 h-full transition-all duration-700 ease-out bg-emerald-300" />
                  </div>
                  
                  <div className="mt-2 flex justify-end">
                    <span className={`text-xs font-medium ${calculatePercentage(budgetData.monthly.spentAmount, budgetData.monthly.targetAmount) >= 90 ? "text-neuro-expense" : "text-gray-500"}`}>
                      {calculatePercentage(budgetData.monthly.spentAmount, budgetData.monthly.targetAmount)}%
                    </span>
                  </div>
                </div>
                
                <div className="flex justify-between items-center pt-2 border-t border-gray-100">
                  <span className="text-gray-500 text-sm">지출 가능 금액</span>
                  <span className="font-semibold text-neuro-income">{formatCurrency(budgetData.monthly.remainingAmount)}</span>
                </div>
              </div>
            </TabsContent>
          </Tabs>
        </div>

        {/* 목표 입력 */}
        <h2 className="text-lg font-semibold mb-3 mt-8">목표 입력</h2>
        <BudgetInputCard initialBudgets={{
        daily: budgetData.daily.targetAmount,
        weekly: budgetData.weekly.targetAmount,
        monthly: budgetData.monthly.targetAmount
      }} onSave={handleBudgetGoalUpdate} />

        {/* Budget Progress */}
        <h2 className="text-lg font-semibold mb-3 mt-8">예산 현황</h2>
        <div className="grid gap-4 mb-8">
          <BudgetCard title="이번 달 총 예산" current={850000} total={1500000} />
          <BudgetCard title="식비" current={240000} total={400000} color="neuro-accent-light" />
          <BudgetCard title="교통비" current={190000} total={200000} color="neuro-expense" />
        </div>

        {/* Recent Transactions */}
        <h2 className="text-lg font-semibold mb-3">최근 거래</h2>
        <div className="grid gap-3 mb-6">
          {transactions.map(transaction => <TransactionCard key={transaction.id} transaction={transaction} />)}
        </div>
        
        <div className="flex justify-center mb-6">
          <button className="text-neuro-accent font-medium">모든 거래 보기</button>
        </div>
      </div>

      <AddTransactionButton />
      <NavBar />
    </div>;
};
export default Index;