import { useState, useEffect, useMemo, useCallback } from 'react';
import {
  BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer,
  PieChart, Pie, Cell,
} from 'recharts';
import type { ApiStatsResponse } from '../../types/statistics';
import { getApiStats } from '../../services/statisticsService';
import DateRangeFilter from '../../components/DateRangeFilter';
import { CHART_COLORS_HEX } from '../../constants/chart';
import { useTheme } from '../../hooks/useTheme';
import Badge from '../../components/ui/Badge';

const SERVICE_TAG_CLASSES = [
  'bg-blue-100 text-blue-700 dark:bg-blue-500/15 dark:text-blue-400',
  'bg-emerald-100 text-emerald-700 dark:bg-emerald-500/15 dark:text-emerald-400',
  'bg-amber-100 text-amber-700 dark:bg-amber-500/15 dark:text-amber-400',
  'bg-red-100 text-red-700 dark:bg-red-500/15 dark:text-red-400',
  'bg-violet-100 text-violet-700 dark:bg-violet-500/15 dark:text-violet-400',
  'bg-cyan-100 text-cyan-700 dark:bg-cyan-500/15 dark:text-cyan-400',
];

const METHOD_CLASS: Record<string, string> = {
  GET: 'bg-blue-100 text-blue-800 dark:bg-blue-500/15 dark:text-blue-400',
  POST: 'bg-green-100 text-green-800 dark:bg-green-500/15 dark:text-green-400',
  PUT: 'bg-amber-100 text-amber-800 dark:bg-amber-500/15 dark:text-amber-400',
  DELETE: 'bg-red-100 text-red-800 dark:bg-red-500/15 dark:text-red-400',
  PATCH: 'bg-purple-100 text-purple-800 dark:bg-purple-500/15 dark:text-purple-400',
};

const getToday = () => new Date().toISOString().slice(0, 10);

const ApiStatsPage = () => {
  const { theme } = useTheme();
  const chartColors = CHART_COLORS_HEX[theme];
  const [startDate, setStartDate] = useState(getToday());
  const [endDate, setEndDate] = useState(getToday());
  const [data, setData] = useState<ApiStatsResponse | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  const fetchData = useCallback(async () => {
    setIsLoading(true);
    try {
      const res = await getApiStats(startDate, endDate);
      if (res.success && res.data) {
        setData(res.data);
      }
    } finally {
      setIsLoading(false);
    }
  }, [startDate, endDate]);

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

  const handlePreset = (days: number) => {
    const today = getToday();
    if (days === 0) {
      setStartDate(today);
    } else {
      const d = new Date();
      d.setDate(d.getDate() - days);
      setStartDate(d.toISOString().slice(0, 10));
    }
    setEndDate(today);
  };

  const serviceColorMap = useMemo(() => {
    if (!data) return {};
    const serviceNames = [...new Set(data.topApis.map((a) => a.serviceName))];
    const map: Record<string, { tag: string; bar: string }> = {};
    serviceNames.forEach((name, i) => {
      map[name] = {
        tag: SERVICE_TAG_CLASSES[i % SERVICE_TAG_CLASSES.length],
        bar: chartColors[i % chartColors.length],
      };
    });
    return map;
  }, [data, chartColors]);

  const statusChartData = useMemo(() => {
    if (!data) return [];
    return data.statusCodeDistribution.map((s) => ({
      statusCode: String(s.statusCode),
      count: s.count,
    }));
  }, [data]);

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-[var(--color-text-secondary)]">로딩 중...</div>
      </div>
    );
  }

  return (
    <div className="max-w-7xl mx-auto">
      <h1 className="text-2xl font-bold text-[var(--color-text-primary)] mb-6">API 통계</h1>

      <DateRangeFilter
        startDate={startDate}
        endDate={endDate}
        onStartDateChange={setStartDate}
        onEndDateChange={setEndDate}
        onPreset={handlePreset}
      />

      {!data ? (
        <p className="text-[var(--color-text-tertiary)] text-center py-20">데이터가 없습니다</p>
      ) : (
        <>
          {/* Charts */}
          <div className="grid grid-cols-2 gap-6 mb-6">
            {/* Chart 1: HTTP Method Distribution */}
            <div className="bg-[var(--color-bg-surface)] rounded-lg shadow p-6">
              <h3 className="text-lg font-semibold text-[var(--color-text-primary)] mb-4">HTTP 메서드 분포</h3>
              {data.methodDistribution.length > 0 ? (
                <ResponsiveContainer width="100%" height={300}>
                  <PieChart>
                    <Pie
                      data={data.methodDistribution}
                      dataKey="count"
                      nameKey="method"
                      innerRadius={60}
                      outerRadius={100}
                    >
                      {data.methodDistribution.map((_, idx) => (
                        <Cell key={idx} fill={chartColors[idx % chartColors.length]} />
                      ))}
                    </Pie>
                    <Tooltip />
                    <Legend layout="vertical" align="right" verticalAlign="middle" />
                  </PieChart>
                </ResponsiveContainer>
              ) : (
                <p className="text-[var(--color-text-tertiary)] text-center py-20">데이터가 없습니다</p>
              )}
            </div>

            {/* Chart 2: HTTP Status Code Distribution */}
            <div className="bg-[var(--color-bg-surface)] rounded-lg shadow p-6">
              <h3 className="text-lg font-semibold text-[var(--color-text-primary)] mb-4">HTTP 상태 코드 분포</h3>
              {statusChartData.length > 0 ? (
                <ResponsiveContainer width="100%" height={300}>
                  <BarChart data={statusChartData}>
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis dataKey="statusCode" />
                    <YAxis />
                    <Tooltip />
                    <Legend />
                    <Bar dataKey="count" fill={chartColors[0]} name="건수" />
                  </BarChart>
                </ResponsiveContainer>
              ) : (
                <p className="text-[var(--color-text-tertiary)] text-center py-20">데이터가 없습니다</p>
              )}
            </div>
          </div>

          {/* Table 1: Top APIs */}
          <div className="bg-[var(--color-bg-surface)] rounded-lg shadow mb-6">
            <div className="p-6 border-b border-[var(--color-border)]">
              <h3 className="text-lg font-semibold text-[var(--color-text-primary)]">API 호출 순위</h3>
            </div>
            {data.topApis.length > 0 ? (
              <div className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead className="bg-[var(--color-bg-base)]">
                    <tr>
                      <th className="px-4 py-3 text-left text-xs font-medium text-[var(--color-text-secondary)] uppercase">순위</th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-[var(--color-text-secondary)] uppercase">서비스</th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-[var(--color-text-secondary)] uppercase">API</th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-[var(--color-text-secondary)] uppercase">메서드</th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-[var(--color-text-secondary)] uppercase">호출 수</th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-[var(--color-text-secondary)] uppercase">평균 응답시간</th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-[var(--color-text-secondary)] uppercase">성공률</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-[var(--color-border)]">
                    {data.topApis.slice(0, 20).map((api, idx) => {
                      const maxCount = data.topApis[0]?.callCount || 1;
                      const pct = (api.callCount / maxCount) * 100;
                      const colors = serviceColorMap[api.serviceName] || { tag: SERVICE_TAG_CLASSES[0], bar: chartColors[0] };
                      return (
                        <tr key={idx} className="hover:bg-[var(--color-bg-base)]">
                          <td className="px-4 py-3 text-[var(--color-text-secondary)]">{idx + 1}</td>
                          <td className="px-4 py-3">
                            <Badge className={colors.tag}>
                              {api.serviceName}
                            </Badge>
                          </td>
                          <td className="px-4 py-3 text-[var(--color-text-primary)] truncate max-w-[250px]" title={api.apiName}>
                            {api.apiName}
                          </td>
                          <td className="px-4 py-3">
                            <Badge className={METHOD_CLASS[api.requestMethod]}>
                              {api.requestMethod}
                            </Badge>
                          </td>
                          <td className="px-4 py-3 text-[var(--color-text-primary)]">
                            <div className="flex items-center gap-2">
                              <div className="w-24 bg-[var(--color-bg-base)] rounded-full h-4">
                                <div className="h-4 rounded-full" style={{ width: `${pct}%`, backgroundColor: colors.bar }} />
                              </div>
                              <span>{api.callCount.toLocaleString()}</span>
                            </div>
                          </td>
                          <td className="px-4 py-3 text-[var(--color-text-primary)]">{api.avgResponseTime.toFixed(0)}ms</td>
                          <td className="px-4 py-3 text-[var(--color-text-primary)]">{api.successRate.toFixed(1)}%</td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            ) : (
              <p className="text-[var(--color-text-tertiary)] text-center py-8">데이터가 없습니다</p>
            )}
          </div>

          {/* Table 2: Top Error APIs */}
          <div className="bg-[var(--color-bg-surface)] rounded-lg shadow">
            <div className="p-6 border-b border-[var(--color-border)]">
              <h3 className="text-lg font-semibold text-[var(--color-text-primary)]">API 에러 순위</h3>
            </div>
            {data.topErrorApis.length > 0 ? (
              <div className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead className="bg-[var(--color-bg-base)]">
                    <tr>
                      <th className="px-4 py-3 text-left text-xs font-medium text-[var(--color-text-secondary)] uppercase">순위</th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-[var(--color-text-secondary)] uppercase">서비스</th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-[var(--color-text-secondary)] uppercase">API</th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-[var(--color-text-secondary)] uppercase">에러 수</th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-[var(--color-text-secondary)] uppercase">전체 수</th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-[var(--color-text-secondary)] uppercase">에러율</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-[var(--color-border)]">
                    {data.topErrorApis.slice(0, 10).map((api, idx) => {
                      const colors = serviceColorMap[api.serviceName] || { tag: SERVICE_TAG_CLASSES[0], bar: chartColors[0] };
                      return (
                        <tr key={idx} className="hover:bg-[var(--color-bg-base)]">
                          <td className="px-4 py-3 text-[var(--color-text-secondary)]">{idx + 1}</td>
                          <td className="px-4 py-3">
                            <Badge className={colors.tag}>
                              {api.serviceName}
                            </Badge>
                          </td>
                          <td className="px-4 py-3 text-[var(--color-text-primary)]" title={api.apiName}>{api.apiName}</td>
                          <td className="px-4 py-3 text-red-600">{api.errorCount.toLocaleString()}</td>
                          <td className="px-4 py-3 text-[var(--color-text-primary)]">{api.totalCount.toLocaleString()}</td>
                          <td className="px-4 py-3 text-red-600">{api.errorRate.toFixed(1)}%</td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            ) : (
              <p className="text-[var(--color-text-tertiary)] text-center py-8">데이터가 없습니다</p>
            )}
          </div>
        </>
      )}
    </div>
  );
};

export default ApiStatsPage;
