"use client";

/**
 * 비용 유형별 통계 대시보드
 * 구매/설치/수리/유지보수/폐기 등 비용 정산 현황
 */

import { useState, useEffect, useCallback } from "react";
import {
  BarChart3,
  TrendingUp,
  TrendingDown,
  Package,
  Wrench,
  Settings,
  Trash2,
  DollarSign,
  Calendar,
  RefreshCw,
} from "lucide-react";

import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Badge } from "@/components/ui/badge";
import { Progress } from "@/components/ui/progress";
import { toast } from "sonner";

import { getCostTypeStats, CostTypeStatsResponse, CostType, costTypeLabels } from "@/lib/api/taxInvoice";

// 비용 유형별 아이콘
const costTypeIcons: Record<CostType, React.ReactNode> = {
  purchase: <Package className="h-4 w-4" />,
  installation: <Settings className="h-4 w-4" />,
  repair: <Wrench className="h-4 w-4" />,
  maintenance: <Settings className="h-4 w-4" />,
  disposal: <Trash2 className="h-4 w-4" />,
  other: <DollarSign className="h-4 w-4" />,
};

// 비용 유형별 색상
const costTypeColors: Record<CostType, string> = {
  purchase: "bg-primary",
  installation: "bg-emerald-500",
  repair: "bg-amber-500",
  maintenance: "bg-purple-500",
  disposal: "bg-destructive",
  other: "bg-muted0",
};

export function CostTypeStats() {
  const [loading, setLoading] = useState(false);
  const [stats, setStats] = useState<CostTypeStatsResponse["data"] | null>(null);
  const [selectedYear, setSelectedYear] = useState<number>(new Date().getFullYear());
  const [selectedMonth, setSelectedMonth] = useState<number | undefined>(undefined);

  // 연도 옵션 생성 (최근 5년)
  const yearOptions = Array.from({ length: 5 }, (_, i) => new Date().getFullYear() - i);

  // 월 옵션 생성
  const monthOptions = Array.from({ length: 12 }, (_, i) => i + 1);

  // 데이터 로드
  const loadStats = useCallback(async () => {
    setLoading(true);
    try {
      const response = await getCostTypeStats(selectedYear, selectedMonth);
      if (response.success) {
        setStats(response.data);
      }
    } catch (error: any) {
      toast.error("통계 로드 실패", { description: error.message });
    } finally {
      setLoading(false);
    }
  }, [selectedYear, selectedMonth]);

  useEffect(() => {
    loadStats();
  }, [loadStats]);

  // 금액 포맷
  const formatAmount = (amount: number) => {
    if (amount >= 100000000) {
      return `${(amount / 100000000).toFixed(1)}억`;
    }
    if (amount >= 10000) {
      return `${(amount / 10000).toFixed(0)}만`;
    }
    return new Intl.NumberFormat("ko-KR").format(amount);
  };

  // 전체 금액 대비 비율 계산
  const getPercentage = (amount: number) => {
    if (!stats?.summary.total_amount || stats.summary.total_amount === 0) return 0;
    return (amount / stats.summary.total_amount) * 100;
  };

  return (
    <div className="space-y-6">
      {/* 헤더 */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-2xl font-bold">비용 정산 현황</h2>
          <p className="text-muted-foreground text-sm">구매/설치/수리/유지보수/폐기 비용 통계</p>
        </div>
        <div className="flex items-center gap-2">
          <Select
            value={String(selectedYear)}
            onValueChange={(v) => setSelectedYear(parseInt(v, 10))}
          >
            <SelectTrigger className="w-[100px]">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {yearOptions.map((year) => (
                <SelectItem key={year} value={String(year)}>
                  {year}년
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
          <Select
            value={selectedMonth ? String(selectedMonth) : "all"}
            onValueChange={(v) => setSelectedMonth(v === "all" ? undefined : parseInt(v, 10))}
          >
            <SelectTrigger className="w-[100px]">
              <SelectValue placeholder="전체" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">전체</SelectItem>
              {monthOptions.map((month) => (
                <SelectItem key={month} value={String(month)}>
                  {month}월
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
          <Button variant="outline" size="icon" onClick={loadStats} disabled={loading}>
            <RefreshCw className={`h-4 w-4 ${loading ? "animate-spin" : ""}`} />
          </Button>
        </div>
      </div>

      {/* 요약 카드 */}
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">총 비용</CardTitle>
            <DollarSign className="text-muted-foreground h-4 w-4" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {formatAmount(stats?.summary.total_amount || 0)}원
            </div>
            <p className="text-muted-foreground text-xs">
              {stats?.summary.total_count || 0}건
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">구매 비용</CardTitle>
            <Package className="h-4 w-4 text-primary" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {formatAmount(stats?.summary.purchase_amount || 0)}원
            </div>
            <Progress
              value={getPercentage(stats?.summary.purchase_amount || 0)}
              className="mt-2 h-1"
            />
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">수리/유지보수</CardTitle>
            <Wrench className="h-4 w-4 text-amber-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {formatAmount((stats?.summary.repair_amount || 0) + (stats?.summary.maintenance_amount || 0))}원
            </div>
            <Progress
              value={getPercentage((stats?.summary.repair_amount || 0) + (stats?.summary.maintenance_amount || 0))}
              className="mt-2 h-1"
            />
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">설치/폐기</CardTitle>
            <Settings className="h-4 w-4 text-emerald-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {formatAmount((stats?.summary.installation_amount || 0) + (stats?.summary.disposal_amount || 0))}원
            </div>
            <Progress
              value={getPercentage((stats?.summary.installation_amount || 0) + (stats?.summary.disposal_amount || 0))}
              className="mt-2 h-1"
            />
          </CardContent>
        </Card>
      </div>

      {/* 비용 유형별 상세 */}
      <Card>
        <CardHeader>
          <CardTitle>비용 유형별 상세</CardTitle>
          <CardDescription>각 비용 유형별 금액 및 비율</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            {stats?.by_cost_type && stats.by_cost_type.length > 0 ? (
              stats.by_cost_type.map((item) => {
                const costType = item.cost_type as CostType;
                const percentage = getPercentage(item.total_amount);
                return (
                  <div key={costType || "none"} className="flex items-center gap-4">
                    <div className="flex w-[120px] items-center gap-2">
                      {costType && costTypeIcons[costType]}
                      <span className="text-sm font-medium">
                        {costType ? costTypeLabels[costType] : "미분류"}
                      </span>
                    </div>
                    <div className="flex-1">
                      <div className="flex items-center gap-2">
                        <div className="flex-1 h-3 rounded-full bg-muted overflow-hidden">
                          <div
                            className={`h-full ${costType ? costTypeColors[costType] : "bg-muted-foreground"}`}
                            style={{ width: `${Math.max(percentage, 2)}%` }}
                          />
                        </div>
                        <span className="w-[50px] text-right text-sm text-muted-foreground">
                          {percentage.toFixed(1)}%
                        </span>
                      </div>
                    </div>
                    <div className="w-[120px] text-right">
                      <div className="font-mono text-sm font-semibold">
                        {formatAmount(item.total_amount)}원
                      </div>
                      <div className="text-xs text-muted-foreground">{item.count}건</div>
                    </div>
                  </div>
                );
              })
            ) : (
              <div className="text-center py-8 text-muted-foreground">
                데이터가 없습니다.
              </div>
            )}
          </div>
        </CardContent>
      </Card>

      {/* 월별 추이 */}
      {!selectedMonth && stats?.by_month && stats.by_month.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle>월별 비용 추이</CardTitle>
            <CardDescription>{selectedYear}년 월별 비용 현황</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="space-y-3">
              {/* 월별 그룹핑 */}
              {Array.from(new Set(stats.by_month.map((item) => item.year_month)))
                .sort()
                .reverse()
                .slice(0, 6)
                .map((yearMonth) => {
                  const monthData = stats.by_month.filter((item) => item.year_month === yearMonth);
                  const monthTotal = monthData.reduce((sum, item) => sum + item.total_amount, 0);
                  const [year, month] = yearMonth.split("-");
                  
                  return (
                    <div key={yearMonth} className="flex items-center gap-4 py-2 border-b last:border-0">
                      <div className="w-[80px] text-sm font-medium">
                        {month}월
                      </div>
                      <div className="flex-1 flex gap-1">
                        {monthData.map((item) => {
                          const costType = item.cost_type as CostType;
                          const width = monthTotal > 0 ? (item.total_amount / monthTotal) * 100 : 0;
                          return (
                            <div
                              key={costType || "none"}
                              className={`h-6 ${costType ? costTypeColors[costType] : "bg-muted-foreground"} rounded`}
                              style={{ width: `${Math.max(width, 5)}%` }}
                              title={`${costType ? costTypeLabels[costType] : "미분류"}: ${formatAmount(item.total_amount)}원`}
                            />
                          );
                        })}
                      </div>
                      <div className="w-[100px] text-right font-mono text-sm">
                        {formatAmount(monthTotal)}원
                      </div>
                    </div>
                  );
                })}
            </div>
            
            {/* 범례 */}
            <div className="mt-4 flex flex-wrap gap-3 pt-4 border-t">
              {Object.entries(costTypeLabels).map(([key, label]) => (
                <div key={key} className="flex items-center gap-1.5">
                  <div className={`w-3 h-3 rounded ${costTypeColors[key as CostType]}`} />
                  <span className="text-xs text-muted-foreground">{label}</span>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  );
}

