'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { DashboardLayout } from '@/components/layout/dashboard-layout';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { DonutChart } from '@/components/charts';
import { Wallet, TrendingUp, Briefcase, RefreshCw } from 'lucide-react';
import { api } from '@/lib/api';

interface HoldingWithValue {
  ticker: string;
  current_ratio: number | null;
  value: number | null;
  profit_loss_ratio: number | null;
}

interface PortfolioDetail {
  id: number;
  name: string;
  portfolio_type: string;
  total_value: number | null;
  total_invested: number | null;
  total_profit_loss: number | null;
  holdings: HoldingWithValue[];
}

interface PortfolioSummary {
  id: number;
  name: string;
  portfolio_type: string;
}

const CHART_COLORS = [
  '#3b82f6', '#8b5cf6', '#10b981', '#f59e0b', '#ef4444', '#06b6d4',
];

const formatKRW = (value: number) => {
  if (value >= 100000000) {
    return `${(value / 100000000).toFixed(1)}억`;
  }
  if (value >= 10000) {
    return `${Math.round(value / 10000)}만`;
  }
  return value.toLocaleString();
};

export default function DashboardPage() {
  const router = useRouter();
  const [loading, setLoading] = useState(true);
  const [portfolios, setPortfolios] = useState<PortfolioDetail[]>([]);

  useEffect(() => {
    const init = async () => {
      try {
        await api.getCurrentUser();
        const summaries = await api.get<PortfolioSummary[]>('/api/portfolios');

        const details = await Promise.all(
          summaries.map(async (p) => {
            try {
              return await api.get<PortfolioDetail>(`/api/portfolios/${p.id}/detail`);
            } catch {
              return {
                ...p,
                total_value: null,
                total_invested: null,
                total_profit_loss: null,
                holdings: [],
              } as PortfolioDetail;
            }
          })
        );
        setPortfolios(details);
      } catch {
        router.push('/login');
      } finally {
        setLoading(false);
      }
    };
    init();
  }, [router]);

  if (loading) {
    return null; // DashboardLayout handles skeleton
  }

  const totalValue = portfolios.reduce((sum, p) => sum + (p.total_value ?? 0), 0);
  const totalInvested = portfolios.reduce((sum, p) => sum + (p.total_invested ?? 0), 0);
  const totalProfitLoss = portfolios.reduce((sum, p) => sum + (p.total_profit_loss ?? 0), 0);
  const totalReturnPercent = totalInvested > 0 ? (totalProfitLoss / totalInvested) * 100 : 0;

  // Aggregate holdings for donut chart
  const allHoldings = portfolios.flatMap((p) => p.holdings);
  const holdingsByTicker: Record<string, number> = {};
  for (const h of allHoldings) {
    if (h.value && h.value > 0) {
      holdingsByTicker[h.ticker] = (holdingsByTicker[h.ticker] ?? 0) + h.value;
    }
  }
  const donutData = Object.entries(holdingsByTicker)
    .sort((a, b) => b[1] - a[1])
    .slice(0, 6)
    .map(([ticker, value], i) => ({
      name: ticker,
      value: totalValue > 0 ? (value / totalValue) * 100 : 0,
      color: CHART_COLORS[i % CHART_COLORS.length],
    }));

  // Add "기타" if there are more holdings
  const topValue = donutData.reduce((s, d) => s + d.value, 0);
  if (topValue < 100 && topValue > 0) {
    donutData.push({ name: '기타', value: 100 - topValue, color: '#6b7280' });
  }

  // Portfolio comparison data
  const portfolioComparison = portfolios
    .filter((p) => p.total_invested && p.total_invested > 0)
    .map((p) => ({
      name: p.name,
      value: ((p.total_profit_loss ?? 0) / (p.total_invested ?? 1)) * 100,
    }));

  return (
    <DashboardLayout>
      <div className="space-y-6">
        {/* Summary Cards */}
        <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>
              <Wallet className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">
                {totalValue > 0 ? `₩${formatKRW(totalValue)}` : '-'}
              </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 className="text-sm font-medium">총 수익률</CardTitle>
              <TrendingUp className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className={`text-2xl font-bold ${totalReturnPercent >= 0 ? 'text-green-600' : 'text-red-600'}`}>
                {totalInvested > 0 ? `${totalReturnPercent >= 0 ? '+' : ''}${totalReturnPercent.toFixed(1)}%` : '-'}
              </div>
              <p className="text-xs text-muted-foreground">
                {totalProfitLoss !== 0 ? `${totalProfitLoss >= 0 ? '+' : ''}₩${formatKRW(Math.abs(totalProfitLoss))}` : '투자 후 확인 가능'}
              </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>
              <Briefcase className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{portfolios.length}</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 className="text-sm font-medium">총 종목 수</CardTitle>
              <RefreshCw className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{Object.keys(holdingsByTicker).length}</div>
              <p className="text-xs text-muted-foreground">보유 중인 종목</p>
            </CardContent>
          </Card>
        </div>

        {/* Main Content */}
        <div className="grid gap-4 md:grid-cols-2">
          {/* Asset Allocation */}
          <Card>
            <CardHeader>
              <CardTitle>자산 배분</CardTitle>
            </CardHeader>
            <CardContent>
              {donutData.length > 0 ? (
                <DonutChart
                  data={donutData}
                  height={280}
                  innerRadius={50}
                  outerRadius={90}
                />
              ) : (
                <div className="flex items-center justify-center h-64 text-muted-foreground">
                  <div className="text-center">
                    <p className="mb-2">보유 종목이 없습니다</p>
                    <Link href="/portfolio" className="text-primary hover:underline text-sm">
                      포트폴리오 관리하기
                    </Link>
                  </div>
                </div>
              )}
            </CardContent>
          </Card>

          {/* Portfolio List */}
          <Card>
            <CardHeader>
              <CardTitle>포트폴리오 현황</CardTitle>
            </CardHeader>
            <CardContent>
              {portfolios.length > 0 ? (
                <div className="space-y-4">
                  {portfolios.map((p) => {
                    const returnPct = p.total_invested && p.total_invested > 0
                      ? ((p.total_profit_loss ?? 0) / p.total_invested) * 100
                      : null;
                    return (
                      <Link key={p.id} href={`/portfolio/${p.id}`} className="block">
                        <div className="flex items-center justify-between p-3 rounded-lg bg-muted/50 hover:bg-muted transition-colors">
                          <div className="flex-1">
                            <div className="flex items-center gap-2">
                              <p className="text-sm font-medium">{p.name}</p>
                              <span className={`text-xs px-1.5 py-0.5 rounded ${
                                p.portfolio_type === 'pension'
                                  ? 'bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-200'
                                  : 'bg-muted text-muted-foreground'
                              }`}>
                                {p.portfolio_type === 'pension' ? '퇴직연금' : '일반'}
                              </span>
                            </div>
                            <p className="text-xs text-muted-foreground mt-1">
                              {p.holdings.length}개 종목
                            </p>
                          </div>
                          <div className="text-right">
                            <p className="text-sm font-medium">
                              {p.total_value ? `₩${formatKRW(p.total_value)}` : '-'}
                            </p>
                            {returnPct !== null && (
                              <p className={`text-xs ${returnPct >= 0 ? 'text-green-600' : 'text-red-600'}`}>
                                {returnPct >= 0 ? '+' : ''}{returnPct.toFixed(1)}%
                              </p>
                            )}
                          </div>
                        </div>
                      </Link>
                    );
                  })}
                </div>
              ) : (
                <div className="flex items-center justify-center h-64 text-muted-foreground">
                  <div className="text-center">
                    <Briefcase className="h-8 w-8 mx-auto mb-2 text-muted-foreground/50" />
                    <p className="mb-2">아직 포트폴리오가 없습니다</p>
                    <Link href="/portfolio/new" className="text-primary hover:underline text-sm">
                      첫 포트폴리오 만들기
                    </Link>
                  </div>
                </div>
              )}
            </CardContent>
          </Card>
        </div>

        {/* Portfolio Comparison */}
        {portfolioComparison.length > 1 && (
          <Card>
            <CardHeader>
              <CardTitle>포트폴리오 수익률 비교</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-3">
                {portfolioComparison.map((p, i) => (
                  <div key={i} className="flex items-center gap-4">
                    <span className="text-sm w-32 truncate">{p.name}</span>
                    <div className="flex-1 bg-muted rounded-full h-4 overflow-hidden">
                      <div
                        className={`h-full rounded-full ${p.value >= 0 ? 'bg-green-500' : 'bg-red-500'}`}
                        style={{ width: `${Math.min(Math.abs(p.value), 100)}%` }}
                      />
                    </div>
                    <span className={`text-sm font-medium w-16 text-right ${p.value >= 0 ? 'text-green-600' : 'text-red-600'}`}>
                      {p.value >= 0 ? '+' : ''}{p.value.toFixed(1)}%
                    </span>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        )}
      </div>
    </DashboardLayout>
  );
}
