'use client';

import { useEffect, useState, useCallback } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { api } from '@/lib/api';
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  PieChart,
  Pie,
  Cell,
  Legend,
} from 'recharts';

interface DashboardSummary {
  totalTrainings: number;
  completedTrainings: number;
  cancelledTrainings: number;
  totalClients: number;
  newClients: number;
  totalSalesAmount: number;
  paidSalesAmount: number;
  upcomingTrainings: number;
  sleepingClients: number;
}

interface FunnelConversion {
  newToAssigned: number;
  assignedToCompleted: number;
  completedToRegular: number;
  totalNew: number;
  totalAssigned: number;
  totalCompleted: number;
  totalRegular: number;
  perTrainer: TrainerFunnelBreakdown[];
}

interface TrainerFunnelBreakdown {
  trainerId: string;
  trainerName: string;
  totalNew: number;
  totalAssigned: number;
  totalCompleted: number;
  totalRegular: number;
  newToAssigned: number;
  assignedToCompleted: number;
  completedToRegular: number;
}

function formatNumber(n: number): string {
  return n.toLocaleString('ru-RU');
}

function formatCurrency(n: number): string {
  return n.toLocaleString('ru-RU', { style: 'currency', currency: 'RUB', maximumFractionDigits: 0 });
}

export default function AnalyticsPage() {
  const [summary, setSummary] = useState<DashboardSummary | null>(null);
  const [funnel, setFunnel] = useState<FunnelConversion | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const loadData = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const [summaryData, funnelData] = await Promise.all([
        api.get<DashboardSummary>('/stats/summary'),
        api.get<FunnelConversion>('/stats/funnel'),
      ]);
      setSummary(summaryData);
      setFunnel(funnelData);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Ошибка загрузки данных');
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    void loadData();
  }, [loadData]);

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[#FF6B00]" />
      </div>
    );
  }

  if (error || !summary) {
    return (
      <div className="flex flex-col items-center justify-center h-64 gap-4">
        <p className="text-[#E53935]">{error ?? 'Данные не получены'}</p>
        <button
          onClick={() => void loadData()}
          className="rounded-xl bg-[#FF6B00] px-4 py-2 text-sm text-white hover:bg-[#E55F00]"
        >
          Попробовать снова
        </button>
      </div>
    );
  }

  const activeClients = summary.totalClients - summary.sleepingClients - summary.newClients;

  const clientBreakdown = [
    { name: 'Активные', value: Math.max(0, activeClients), color: '#43A047' },
    { name: 'Новые', value: summary.newClients, color: '#FF6B00' },
    { name: 'Спящие', value: summary.sleepingClients, color: '#E53935' },
  ].filter((d) => d.value > 0);

  const funnelStages = funnel
    ? [
        { name: 'Новые', count: funnel.totalNew, color: '#3B82F6' },
        { name: 'Назначено', count: funnel.totalAssigned, color: '#FF6B00' },
        { name: 'Проведено', count: funnel.totalCompleted, color: '#F59E0B' },
        { name: 'Постоянные', count: funnel.totalRegular, color: '#43A047' },
      ]
    : [];

  const trainingBreakdown = [
    { name: 'Проведено', value: summary.completedTrainings, color: '#43A047' },
    { name: 'Отменено', value: summary.cancelledTrainings, color: '#E53935' },
    {
      name: 'Прочие',
      value: summary.totalTrainings - summary.completedTrainings - summary.cancelledTrainings,
      color: '#9CA3AF',
    },
  ].filter((d) => d.value > 0);

  return (
    <div className="space-y-6">
      {/* KPI Cards */}
      <div className="grid grid-cols-2 gap-4 lg:grid-cols-4">
        <MetricCard label="Всего клиентов" value={formatNumber(summary.totalClients)} />
        <MetricCard
          label="Активных"
          value={formatNumber(Math.max(0, activeClients))}
          color="#43A047"
        />
        <MetricCard label="Новых за период" value={formatNumber(summary.newClients)} color="#FF6B00" />
        <MetricCard label="Спящих" value={formatNumber(summary.sleepingClients)} color="#E53935" />
      </div>

      <div className="grid grid-cols-2 gap-4 lg:grid-cols-4">
        <MetricCard label="Всего тренировок" value={formatNumber(summary.totalTrainings)} />
        <MetricCard
          label="Проведённых"
          value={formatNumber(summary.completedTrainings)}
          color="#43A047"
        />
        <MetricCard
          label="Ближайших (7 дн)"
          value={formatNumber(summary.upcomingTrainings)}
          color="#FF6B00"
        />
        <MetricCard label="Продажи (оплач.)" value={formatCurrency(summary.paidSalesAmount)} color="#43A047" />
      </div>

      {/* Charts Row */}
      <div className="grid gap-6 lg:grid-cols-2">
        {/* Funnel Chart */}
        <Card>
          <CardHeader>
            <CardTitle>Воронка конверсии</CardTitle>
          </CardHeader>
          <CardContent>
            {funnelStages.length === 0 ? (
              <p className="flex h-64 items-center justify-center text-[#6B7280]">
                Нет данных воронки
              </p>
            ) : (
              <div className="h-72">
                <ResponsiveContainer width="100%" height="100%">
                  <BarChart data={funnelStages} margin={{ top: 5, right: 20, left: 0, bottom: 5 }}>
                    <CartesianGrid strokeDasharray="3 3" stroke="#E5E7EB" />
                    <XAxis dataKey="name" tick={{ fontSize: 12 }} />
                    <YAxis tick={{ fontSize: 12 }} />
                    <Tooltip
                      formatter={(value) => [formatNumber(Number(value ?? 0)), 'Клиентов']}
                      contentStyle={{ borderRadius: 8, border: '1px solid #E5E7EB' }}
                    />
                    <Bar dataKey="count" radius={[6, 6, 0, 0]}>
                      {funnelStages.map((entry, index) => (
                        <Cell key={index} fill={entry.color} />
                      ))}
                    </Bar>
                  </BarChart>
                </ResponsiveContainer>
              </div>
            )}
            {funnel && (
              <div className="mt-4 grid grid-cols-3 gap-2 text-center text-xs">
                <div>
                  <p className="text-[#6B7280]">Новые → Назначено</p>
                  <p className="text-lg font-semibold">{funnel.newToAssigned}%</p>
                </div>
                <div>
                  <p className="text-[#6B7280]">Назначено → Проведено</p>
                  <p className="text-lg font-semibold">{funnel.assignedToCompleted}%</p>
                </div>
                <div>
                  <p className="text-[#6B7280]">Проведено → Постоянные</p>
                  <p className="text-lg font-semibold">{funnel.completedToRegular}%</p>
                </div>
              </div>
            )}
          </CardContent>
        </Card>

        {/* Client Breakdown Pie Chart */}
        <Card>
          <CardHeader>
            <CardTitle>Распределение клиентов</CardTitle>
          </CardHeader>
          <CardContent>
            {clientBreakdown.length === 0 ? (
              <p className="flex h-64 items-center justify-center text-[#6B7280]">
                Нет данных
              </p>
            ) : (
              <div className="h-72">
                <ResponsiveContainer width="100%" height="100%">
                  <PieChart>
                    <Pie
                      data={clientBreakdown}
                      cx="50%"
                      cy="50%"
                      innerRadius={60}
                      outerRadius={100}
                      dataKey="value"
                      label={(props) => `${props.name ?? ''}: ${formatNumber(Number(props.value ?? 0))}`}
                    >
                      {clientBreakdown.map((entry, index) => (
                        <Cell key={index} fill={entry.color} />
                      ))}
                    </Pie>
                    <Tooltip formatter={(value) => formatNumber(Number(value ?? 0))} />
                    <Legend />
                  </PieChart>
                </ResponsiveContainer>
              </div>
            )}
          </CardContent>
        </Card>
      </div>

      {/* Training Breakdown */}
      <Card>
        <CardHeader>
          <CardTitle>Тренировки по статусам</CardTitle>
        </CardHeader>
        <CardContent>
          {trainingBreakdown.length === 0 ? (
            <p className="flex h-64 items-center justify-center text-[#6B7280]">
              Нет данных
            </p>
          ) : (
            <div className="h-64">
              <ResponsiveContainer width="100%" height="100%">
                <BarChart data={trainingBreakdown} layout="vertical" margin={{ top: 5, right: 30, left: 80, bottom: 5 }}>
                  <CartesianGrid strokeDasharray="3 3" stroke="#E5E7EB" />
                  <XAxis type="number" tick={{ fontSize: 12 }} />
                  <YAxis type="category" dataKey="name" tick={{ fontSize: 12 }} />
                  <Tooltip
                    formatter={(value) => [formatNumber(Number(value ?? 0)), 'Тренировок']}
                    contentStyle={{ borderRadius: 8, border: '1px solid #E5E7EB' }}
                  />
                  <Bar dataKey="value" radius={[0, 6, 6, 0]}>
                    {trainingBreakdown.map((entry, index) => (
                      <Cell key={index} fill={entry.color} />
                    ))}
                  </Bar>
                </BarChart>
              </ResponsiveContainer>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Per-Trainer Funnel Table */}
      {funnel && funnel.perTrainer.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle>Конверсия по тренерам</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead>
                  <tr className="border-b border-[#E5E7EB]">
                    <th className="pb-3 text-left font-medium text-[#6B7280]">Тренер</th>
                    <th className="pb-3 text-right font-medium text-[#6B7280]">Новые</th>
                    <th className="pb-3 text-right font-medium text-[#6B7280]">Назначено</th>
                    <th className="pb-3 text-right font-medium text-[#6B7280]">Проведено</th>
                    <th className="pb-3 text-right font-medium text-[#6B7280]">Постоянные</th>
                    <th className="pb-3 text-right font-medium text-[#6B7280]">Нов→Назн</th>
                    <th className="pb-3 text-right font-medium text-[#6B7280]">Назн→Пров</th>
                    <th className="pb-3 text-right font-medium text-[#6B7280]">Пров→Пост</th>
                  </tr>
                </thead>
                <tbody>
                  {funnel.perTrainer.map((t) => (
                    <tr key={t.trainerId} className="border-b border-[#E5E7EB] last:border-0">
                      <td className="py-3 font-medium text-gray-900">{t.trainerName}</td>
                      <td className="py-3 text-right">{t.totalNew}</td>
                      <td className="py-3 text-right">{t.totalAssigned}</td>
                      <td className="py-3 text-right">{t.totalCompleted}</td>
                      <td className="py-3 text-right">{t.totalRegular}</td>
                      <td className="py-3 text-right">{t.newToAssigned}%</td>
                      <td className="py-3 text-right">{t.assignedToCompleted}%</td>
                      <td className="py-3 text-right">{t.completedToRegular}%</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </CardContent>
        </Card>
      )}

      {/* Sales Summary */}
      <div className="grid gap-4 lg:grid-cols-3">
        <Card>
          <CardContent className="p-4">
            <p className="text-sm text-[#6B7280]">Общая сумма продаж</p>
            <p className="text-2xl font-bold text-gray-900">{formatCurrency(summary.totalSalesAmount)}</p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <p className="text-sm text-[#6B7280]">Оплачено</p>
            <p className="text-2xl font-bold text-[#43A047]">{formatCurrency(summary.paidSalesAmount)}</p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <p className="text-sm text-[#6B7280]">Не оплачено</p>
            <p className="text-2xl font-bold text-[#E53935]">
              {formatCurrency(summary.totalSalesAmount - summary.paidSalesAmount)}
            </p>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}

function MetricCard({
  label,
  value,
  color,
}: {
  label: string;
  value: string;
  color?: string;
}) {
  return (
    <Card>
      <CardContent className="p-4">
        <p className="text-sm text-[#6B7280]">{label}</p>
        <p className="text-2xl font-bold" style={color ? { color } : { color: '#111827' }}>
          {value}
        </p>
      </CardContent>
    </Card>
  );
}
