import { useState, useEffect, useMemo, useCallback } from 'react';
import {
  BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer,
  LineChart, Line,
} from 'recharts';
import type { TenantStatsResponse } from '../../types/statistics';
import { getTenantStats } from '../../services/statisticsService';
import DateRangeFilter from '../../components/DateRangeFilter';
import { CHART_COLORS_HEX } from '../../constants/chart';
import { useTheme } from '../../hooks/useTheme';

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

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

  const fetchData = useCallback(async () => {
    setIsLoading(true);
    try {
      const res = await getTenantStats(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 dailyTrendPivoted = useMemo(() => {
    if (!data) return { data: [], tenantNames: [] };
    const tenantNames = [...new Set(data.dailyTrend.map((e) => e.tenantName))];
    const byDate: Record<string, Record<string, number | string>> = {};
    for (const item of data.dailyTrend) {
      if (!byDate[item.date]) {
        byDate[item.date] = { date: item.date };
      }
      byDate[item.date][item.tenantName] = item.count;
    }
    return { data: Object.values(byDate), tenantNames };
  }, [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">테넌트 통계</h1>

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

      {!data || data.tenantStats.length === 0 ? (
        <p className="text-[var(--color-text-tertiary)] text-center py-20">데이터가 없습니다</p>
      ) : (
        <>
          {/* Summary Cards */}
          <div className="flex gap-4 mb-6">
            {data.tenantStats.map((tenant) => (
              <div key={tenant.tenantId} className="flex-1 bg-[var(--color-bg-surface)] rounded-lg shadow p-6">
                <p className="text-sm font-medium text-[var(--color-text-secondary)]">{tenant.tenantName || 'Unknown'}</p>
                <p className="text-2xl font-bold text-[var(--color-text-primary)] mt-1">
                  {tenant.totalRequests.toLocaleString()}
                </p>
                <div className="flex items-center gap-3 mt-2 text-sm">
                  <span className="text-[var(--color-text-secondary)]">사용자 {tenant.activeUsers}</span>
                  <span className="text-green-600">성공 {tenant.successRate.toFixed(1)}%</span>
                </div>
              </div>
            ))}
          </div>

          {/* Charts */}
          <div className="grid grid-cols-2 gap-6 mb-6">
            {/* Chart 1: Daily Tenant Trend */}
            <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">일별 테넌트 요청 추이</h3>
              {dailyTrendPivoted.data.length > 0 ? (
                <ResponsiveContainer width="100%" height={300}>
                  <LineChart data={dailyTrendPivoted.data}>
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis dataKey="date" />
                    <YAxis />
                    <Tooltip />
                    <Legend />
                    {dailyTrendPivoted.tenantNames.map((name, idx) => (
                      <Line
                        key={name}
                        type="monotone"
                        dataKey={name}
                        stroke={chartColors[idx % chartColors.length]}
                      />
                    ))}
                  </LineChart>
                </ResponsiveContainer>
              ) : (
                <p className="text-[var(--color-text-tertiary)] text-center py-20">데이터가 없습니다</p>
              )}
            </div>

            {/* Chart 2: Tenant API Key Stats */}
            <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">테넌트별 API Key 현황</h3>
              {data.apiKeyStats.length > 0 ? (
                <ResponsiveContainer width="100%" height={300}>
                  <BarChart data={data.apiKeyStats}>
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis dataKey="tenantName" />
                    <YAxis />
                    <Tooltip />
                    <Legend />
                    <Bar dataKey="totalKeys" fill={chartColors[0]} name="전체 키" />
                    <Bar dataKey="activeKeys" fill="#10b981" name="활성 키" />
                  </BarChart>
                </ResponsiveContainer>
              ) : (
                <p className="text-[var(--color-text-tertiary)] text-center py-20">데이터가 없습니다</p>
              )}
            </div>
          </div>

          {/* Table: Tenant Details */}
          <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)]">테넌트 상세</h3>
            </div>
            <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">활성 사용자</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.tenantStats.map((tenant) => (
                    <tr key={tenant.tenantId} className="hover:bg-[var(--color-bg-base)]">
                      <td className="px-4 py-3 text-[var(--color-text-primary)] font-medium">{tenant.tenantName || 'Unknown'}</td>
                      <td className="px-4 py-3 text-[var(--color-text-primary)]">{tenant.totalRequests.toLocaleString()}</td>
                      <td className="px-4 py-3 text-[var(--color-text-primary)]">{tenant.activeUsers}</td>
                      <td className="px-4 py-3 text-[var(--color-text-primary)]">{tenant.successRate.toFixed(1)}%</td>
                      <td className="px-4 py-3 text-[var(--color-text-primary)]">{tenant.avgResponseTime.toFixed(0)}ms</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        </>
      )}
    </div>
  );
};

export default TenantStatsPage;
