import { useState, useEffect, useCallback } from 'react';
import {
  AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer,
  PieChart, Pie, Cell,
} from 'recharts';
import type { UserStatsResponse } from '../../types/statistics';
import { getUserStats } from '../../services/statisticsService';
import DateRangeFilter from '../../components/DateRangeFilter';
import { CHART_COLORS_HEX } from '../../constants/chart';
import { useTheme } from '../../hooks/useTheme';

const ROLE_BADGE: Record<string, string> = {
  ADMIN: 'bg-red-100 text-red-800',
  MANAGER: 'bg-blue-100 text-blue-800',
  USER: 'bg-green-100 text-green-800',
};

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

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

  const fetchData = useCallback(async () => {
    setIsLoading(true);
    try {
      const res = await getUserStats(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);
  };

  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 ? (
        <p className="text-[var(--color-text-tertiary)] text-center py-20">데이터가 없습니다</p>
      ) : (
        <>
          {/* Summary Cards */}
          <div className="flex gap-4 mb-6">
            <div className="flex-1 bg-[var(--color-bg-surface)] rounded-lg shadow p-6">
              <p className="text-sm text-[var(--color-text-secondary)]">전체 사용자</p>
              <p className="text-3xl font-bold text-[var(--color-text-primary)]">{data.totalUsers}</p>
            </div>
            <div className="flex-1 bg-[var(--color-bg-surface)] rounded-lg shadow p-6">
              <p className="text-sm text-[var(--color-text-secondary)]">API Key 보유 사용자</p>
              <p className="text-3xl font-bold text-[var(--color-text-primary)]">{data.usersWithActiveKey}</p>
            </div>
            <div className="flex-1 bg-[var(--color-bg-surface)] rounded-lg shadow p-6">
              <p className="text-sm text-[var(--color-text-secondary)]">API 요청 사용자</p>
              <p className="text-3xl font-bold text-[var(--color-text-primary)]">{data.totalActiveUsers}</p>
            </div>
          </div>

          {/* Charts */}
          <div className="grid grid-cols-2 gap-6 mb-6">
            {/* Chart 1: Daily Active Users */}
            <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 요청 사용자 추이</h3>
              {data.dailyActiveUsers.length > 0 ? (
                <ResponsiveContainer width="100%" height={300}>
                  <AreaChart data={data.dailyActiveUsers}>
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis dataKey="date" />
                    <YAxis />
                    <Tooltip />
                    <Legend />
                    <Area
                      type="monotone"
                      dataKey="activeUsers"
                      stroke={chartColors[0]}
                      fill={chartColors[0]}
                      fillOpacity={0.3}
                      name="API 요청 사용자"
                    />
                  </AreaChart>
                </ResponsiveContainer>
              ) : (
                <p className="text-[var(--color-text-tertiary)] text-center py-20">데이터가 없습니다</p>
              )}
            </div>

            {/* Chart 2: Role Distribution Donut */}
            <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>
              {data.roleDistribution.length > 0 ? (
                <ResponsiveContainer width="100%" height={300}>
                  <PieChart>
                    <Pie
                      data={data.roleDistribution}
                      dataKey="requestCount"
                      nameKey="role"
                      innerRadius={60}
                      outerRadius={100}
                    >
                      {data.roleDistribution.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>
          </div>

          {/* Table: Top Users */}
          <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)]">상위 사용자 Top 10</h3>
            </div>
            {data.topUsers.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">역할</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.topUsers.slice(0, 10).map((user, idx) => (
                      <tr key={user.userId} 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 text-[var(--color-text-primary)]">{user.userName}</td>
                        <td className="px-4 py-3">
                          <span className={`px-2 py-1 rounded-full text-xs font-medium ${ROLE_BADGE[user.role] ?? 'bg-gray-100 text-gray-800'}`}>
                            {user.role}
                          </span>
                        </td>
                        <td className="px-4 py-3 text-[var(--color-text-primary)]">{user.requestCount.toLocaleString()}</td>
                        <td className="px-4 py-3 text-[var(--color-text-primary)]">{user.successRate.toFixed(1)}%</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            ) : (
              <p className="text-[var(--color-text-tertiary)] text-center py-8">데이터가 없습니다</p>
            )}
          </div>
        </>
      )}
    </div>
  );
};

export default UserStatsPage;
