import React, { useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from './ui/card';
import { Button } from './ui/button';
import { Badge } from './ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from './ui/tabs';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './ui/select';
import {
  FileText,
  TrendingUp,
  TrendingDown,
  DollarSign,
  PieChart,
  Download,
  Printer,
} from 'lucide-react';

export function FinancialStatements() {
  const [selectedYear, setSelectedYear] = useState('2025');
  const [selectedQuarter, setSelectedQuarter] = useState('2Q');

  // 재무상태표 데이터
  const balanceSheet = {
    assets: {
      current: [
        { item: '현금및현금성자산', amount: 1250000000 },
        { item: '매출채권', amount: 850000000 },
        { item: '재고자산', amount: 650000000 },
        { item: '기타유동자산', amount: 180000000 },
      ],
      nonCurrent: [
        { item: '유형자산', amount: 3200000000 },
        { item: '무형자산', amount: 450000000 },
        { item: '투자자산', amount: 320000000 },
      ]
    },
    liabilities: {
      current: [
        { item: '매입채무', amount: 420000000 },
        { item: '단기차입금', amount: 580000000 },
        { item: '기타유동부채', amount: 220000000 },
      ],
      nonCurrent: [
        { item: '장기차입금', amount: 1200000000 },
        { item: '기타비유동부채', amount: 180000000 },
      ]
    },
    equity: [
      { item: '자본금', amount: 1500000000 },
      { item: '자본잉여금', amount: 800000000 },
      { item: '이익잉여금', amount: 2000000000 },
    ]
  };

  // 손익계산서 데이터
  const incomeStatement = {
    revenue: [
      { item: '매출액', amount: 3900000000, percentage: 100 },
      { item: '매출원가', amount: -2340000000, percentage: -60 },
    ],
    grossProfit: 1560000000,
    operatingExpenses: [
      { item: '판매비', amount: -450000000, percentage: -11.5 },
      { item: '관리비', amount: -380000000, percentage: -9.7 },
      { item: '연구개발비', amount: -180000000, percentage: -4.6 },
    ],
    operatingProfit: 550000000,
    nonOperating: [
      { item: '이자수익', amount: 25000000, percentage: 0.6 },
      { item: '이자비용', amount: -48000000, percentage: -1.2 },
      { item: '기타영업외손익', amount: 15000000, percentage: 0.4 },
    ],
    netProfit: 542000000
  };

  // 현금흐름표 데이터
  const cashFlow = {
    operating: [
      { item: '영업활동으로 인한 현금흐름', amount: 680000000 },
      { item: '당기순이익', amount: 542000000 },
      { item: '감가상각비', amount: 220000000 },
      { item: '매출채권의 감소(증가)', amount: -95000000 },
      { item: '재고자산의 감소(증가)', amount: -82000000 },
      { item: '매입채무의 증가(감소)', amount: 95000000 },
    ],
    investing: [
      { item: '투자활동으로 인한 현금흐름', amount: -420000000 },
      { item: '유형자산의 취득', amount: -380000000 },
      { item: '무형자산의 취득', amount: -65000000 },
      { item: '투자자산의 처분', amount: 25000000 },
    ],
    financing: [
      { item: '재무활동으로 인한 현금흐름', amount: -150000000 },
      { item: '단기차입금의 증가(감소)', amount: 100000000 },
      { item: '장기차입금의 증가(감소)', amount: -180000000 },
      { item: '배당금의 지급', amount: -70000000 },
    ]
  };

  const years = ['2025', '2024', '2023'];
  const quarters = ['1Q', '2Q', '3Q', '4Q'];

  const totalCurrentAssets = balanceSheet.assets.current.reduce((sum, item) => sum + item.amount, 0);
  const totalNonCurrentAssets = balanceSheet.assets.nonCurrent.reduce((sum, item) => sum + item.amount, 0);
  const totalAssets = totalCurrentAssets + totalNonCurrentAssets;

  const totalCurrentLiabilities = balanceSheet.liabilities.current.reduce((sum, item) => sum + item.amount, 0);
  const totalNonCurrentLiabilities = balanceSheet.liabilities.nonCurrent.reduce((sum, item) => sum + item.amount, 0);
  const totalLiabilities = totalCurrentLiabilities + totalNonCurrentLiabilities;

  const totalEquity = balanceSheet.equity.reduce((sum, item) => sum + item.amount, 0);

  const formatAmount = (amount: number) => {
    return (amount / 1000000).toFixed(0);
  };

  return (
    <div className="p-6 space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="mb-2">재무제표</h1>
          <p className="text-muted-foreground">
            재무상태표, 손익계산서, 현금흐름표를 조회합니다.
          </p>
        </div>
        <div className="flex gap-2">
          <Select value={selectedYear} onValueChange={setSelectedYear}>
            <SelectTrigger className="w-[100px]">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {years.map((year) => (
                <SelectItem key={year} value={year}>
                  {year}년
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
          <Select value={selectedQuarter} onValueChange={setSelectedQuarter}>
            <SelectTrigger className="w-[100px]">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {quarters.map((quarter) => (
                <SelectItem key={quarter} value={quarter}>
                  {quarter}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
          <Button variant="outline" size="sm">
            <Download className="h-4 w-4 mr-2" />
            Excel
          </Button>
          <Button variant="outline" size="sm">
            <Printer className="h-4 w-4 mr-2" />
            인쇄
          </Button>
        </div>
      </div>

      {/* 주요 재무 지표 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-6">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle>총자산</CardTitle>
            <DollarSign className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{formatAmount(totalAssets)}억원</div>
            <p className="text-xs text-muted-foreground">유동 + 비유동</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle>총부채</CardTitle>
            <TrendingDown className="h-4 w-4 text-orange-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-orange-500">{formatAmount(totalLiabilities)}억원</div>
            <p className="text-xs text-muted-foreground">부채비율 {((totalLiabilities / totalEquity) * 100).toFixed(1)}%</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle>자본총계</CardTitle>
            <TrendingUp className="h-4 w-4 text-green-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-green-500">{formatAmount(totalEquity)}억원</div>
            <p className="text-xs text-muted-foreground">자기자본</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle>당기순이익</CardTitle>
            <PieChart className="h-4 w-4 text-blue-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-blue-500">{formatAmount(incomeStatement.netProfit)}억원</div>
            <p className="text-xs text-muted-foreground">순이익률 {((incomeStatement.netProfit / incomeStatement.revenue[0].amount) * 100).toFixed(1)}%</p>
          </CardContent>
        </Card>
      </div>

      {/* 재무제표 탭 */}
      <Tabs defaultValue="balance" className="space-y-4">
        <TabsList>
          <TabsTrigger value="balance">재무상태표</TabsTrigger>
          <TabsTrigger value="income">손익계산서</TabsTrigger>
          <TabsTrigger value="cashflow">현금흐름표</TabsTrigger>
        </TabsList>

        {/* 재무상태표 */}
        <TabsContent value="balance" className="space-y-4">
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            {/* 자산 */}
            <Card>
              <CardHeader>
                <CardTitle>자산</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div>
                  <p className="font-medium mb-2">유동자산</p>
                  <div className="space-y-1">
                    {balanceSheet.assets.current.map((item, index) => (
                      <div key={index} className="flex justify-between text-sm">
                        <span className="text-muted-foreground pl-4">{item.item}</span>
                        <span>{formatAmount(item.amount)}백만원</span>
                      </div>
                    ))}
                    <div className="flex justify-between font-medium pt-2 border-t">
                      <span>유동자산 계</span>
                      <span>{formatAmount(totalCurrentAssets)}백만원</span>
                    </div>
                  </div>
                </div>

                <div>
                  <p className="font-medium mb-2">비유동자산</p>
                  <div className="space-y-1">
                    {balanceSheet.assets.nonCurrent.map((item, index) => (
                      <div key={index} className="flex justify-between text-sm">
                        <span className="text-muted-foreground pl-4">{item.item}</span>
                        <span>{formatAmount(item.amount)}백만원</span>
                      </div>
                    ))}
                    <div className="flex justify-between font-medium pt-2 border-t">
                      <span>비유동자산 계</span>
                      <span>{formatAmount(totalNonCurrentAssets)}백만원</span>
                    </div>
                  </div>
                </div>

                <div className="flex justify-between font-bold text-lg pt-4 border-t-2">
                  <span>자산총계</span>
                  <span>{formatAmount(totalAssets)}백만원</span>
                </div>
              </CardContent>
            </Card>

            {/* 부채 및 자본 */}
            <Card>
              <CardHeader>
                <CardTitle>부채 및 자본</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div>
                  <p className="font-medium mb-2">유동부채</p>
                  <div className="space-y-1">
                    {balanceSheet.liabilities.current.map((item, index) => (
                      <div key={index} className="flex justify-between text-sm">
                        <span className="text-muted-foreground pl-4">{item.item}</span>
                        <span>{formatAmount(item.amount)}백만원</span>
                      </div>
                    ))}
                    <div className="flex justify-between font-medium pt-2 border-t">
                      <span>유동부채 계</span>
                      <span>{formatAmount(totalCurrentLiabilities)}백만원</span>
                    </div>
                  </div>
                </div>

                <div>
                  <p className="font-medium mb-2">비유동부채</p>
                  <div className="space-y-1">
                    {balanceSheet.liabilities.nonCurrent.map((item, index) => (
                      <div key={index} className="flex justify-between text-sm">
                        <span className="text-muted-foreground pl-4">{item.item}</span>
                        <span>{formatAmount(item.amount)}백만원</span>
                      </div>
                    ))}
                    <div className="flex justify-between font-medium pt-2 border-t">
                      <span>비유동부채 계</span>
                      <span>{formatAmount(totalNonCurrentLiabilities)}백만원</span>
                    </div>
                  </div>
                </div>

                <div>
                  <p className="font-medium mb-2">자본</p>
                  <div className="space-y-1">
                    {balanceSheet.equity.map((item, index) => (
                      <div key={index} className="flex justify-between text-sm">
                        <span className="text-muted-foreground pl-4">{item.item}</span>
                        <span>{formatAmount(item.amount)}백만원</span>
                      </div>
                    ))}
                    <div className="flex justify-between font-medium pt-2 border-t">
                      <span>자본총계</span>
                      <span>{formatAmount(totalEquity)}백만원</span>
                    </div>
                  </div>
                </div>

                <div className="flex justify-between font-bold text-lg pt-4 border-t-2">
                  <span>부채와 자본총계</span>
                  <span>{formatAmount(totalLiabilities + totalEquity)}백만원</span>
                </div>
              </CardContent>
            </Card>
          </div>
        </TabsContent>

        {/* 손익계산서 */}
        <TabsContent value="income">
          <Card>
            <CardHeader>
              <CardTitle>손익계산서</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="space-y-1">
                {incomeStatement.revenue.map((item, index) => (
                  <div key={index} className="flex justify-between text-sm">
                    <span className={item.amount < 0 ? 'text-muted-foreground pl-4' : 'font-medium'}>
                      {item.item}
                    </span>
                    <div className="flex gap-4">
                      <span className="w-24 text-right">{formatAmount(Math.abs(item.amount))}백만원</span>
                      <span className="w-16 text-right text-muted-foreground">{item.percentage}%</span>
                    </div>
                  </div>
                ))}
                <div className="flex justify-between font-medium pt-2 border-t">
                  <span>매출총이익</span>
                  <div className="flex gap-4">
                    <span className="w-24 text-right">{formatAmount(incomeStatement.grossProfit)}백만원</span>
                    <span className="w-16 text-right text-muted-foreground">
                      {((incomeStatement.grossProfit / incomeStatement.revenue[0].amount) * 100).toFixed(1)}%
                    </span>
                  </div>
                </div>
              </div>

              <div className="space-y-1">
                <p className="font-medium mb-2">판매비와 관리비</p>
                {incomeStatement.operatingExpenses.map((item, index) => (
                  <div key={index} className="flex justify-between text-sm">
                    <span className="text-muted-foreground pl-4">{item.item}</span>
                    <div className="flex gap-4">
                      <span className="w-24 text-right">{formatAmount(Math.abs(item.amount))}백만원</span>
                      <span className="w-16 text-right text-muted-foreground">{Math.abs(item.percentage)}%</span>
                    </div>
                  </div>
                ))}
                <div className="flex justify-between font-medium pt-2 border-t">
                  <span>영업이익</span>
                  <div className="flex gap-4">
                    <span className="w-24 text-right text-blue-600">{formatAmount(incomeStatement.operatingProfit)}백만원</span>
                    <span className="w-16 text-right text-muted-foreground">
                      {((incomeStatement.operatingProfit / incomeStatement.revenue[0].amount) * 100).toFixed(1)}%
                    </span>
                  </div>
                </div>
              </div>

              <div className="space-y-1">
                <p className="font-medium mb-2">영업외손익</p>
                {incomeStatement.nonOperating.map((item, index) => (
                  <div key={index} className="flex justify-between text-sm">
                    <span className="text-muted-foreground pl-4">{item.item}</span>
                    <div className="flex gap-4">
                      <span className="w-24 text-right">{formatAmount(Math.abs(item.amount))}백만원</span>
                      <span className="w-16 text-right text-muted-foreground">{Math.abs(item.percentage)}%</span>
                    </div>
                  </div>
                ))}
              </div>

              <div className="flex justify-between font-bold text-lg pt-4 border-t-2">
                <span>당기순이익</span>
                <div className="flex gap-4">
                  <span className="w-24 text-right text-green-600">{formatAmount(incomeStatement.netProfit)}백만원</span>
                  <span className="w-16 text-right text-muted-foreground">
                    {((incomeStatement.netProfit / incomeStatement.revenue[0].amount) * 100).toFixed(1)}%
                  </span>
                </div>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* 현금흐름표 */}
        <TabsContent value="cashflow">
          <Card>
            <CardHeader>
              <CardTitle>현금흐름표</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="space-y-1">
                <p className="font-medium mb-2">영업활동 현금흐름</p>
                {cashFlow.operating.map((item, index) => (
                  <div key={index} className="flex justify-between text-sm">
                    <span className={index === 0 ? 'font-medium' : 'text-muted-foreground pl-4'}>
                      {item.item}
                    </span>
                    <span className={index === 0 ? 'font-medium' : ''}>
                      {formatAmount(item.amount)}백만원
                    </span>
                  </div>
                ))}
              </div>

              <div className="space-y-1">
                <p className="font-medium mb-2">투자활동 현금흐름</p>
                {cashFlow.investing.map((item, index) => (
                  <div key={index} className="flex justify-between text-sm">
                    <span className={index === 0 ? 'font-medium' : 'text-muted-foreground pl-4'}>
                      {item.item}
                    </span>
                    <span className={index === 0 ? 'font-medium' : ''}>
                      {formatAmount(item.amount)}백만원
                    </span>
                  </div>
                ))}
              </div>

              <div className="space-y-1">
                <p className="font-medium mb-2">재무활동 현금흐름</p>
                {cashFlow.financing.map((item, index) => (
                  <div key={index} className="flex justify-between text-sm">
                    <span className={index === 0 ? 'font-medium' : 'text-muted-foreground pl-4'}>
                      {item.item}
                    </span>
                    <span className={index === 0 ? 'font-medium' : ''}>
                      {formatAmount(item.amount)}백만원
                    </span>
                  </div>
                ))}
              </div>

              <div className="flex justify-between font-bold text-lg pt-4 border-t-2">
                <span>현금의 증가(감소)</span>
                <span className="text-blue-600">
                  {formatAmount(
                    cashFlow.operating[0].amount + 
                    cashFlow.investing[0].amount + 
                    cashFlow.financing[0].amount
                  )}백만원
                </span>
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}
