'use client';

import { useEffect, useState, useCallback } from 'react';
import { FileText, Download, Plus, RefreshCw, AlertCircle } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Select } from '@/components/ui/select';
import {
  Dialog, DialogContent, DialogHeader, DialogTitle,
  DialogDescription, DialogFooter,
} from '@/components/ui/dialog';
import { api, ApiError } from '@/lib/api';

interface Report {
  id: string;
  type: string;
  title: string;
  status: string;
  fileUrl: string | null;
  createdAt: string;
  generatedBy: { id: string; firstName: string; lastName: string } | null;
}

const REPORT_TYPES = [
  { value: 'CLIENT_STATUS', label: 'Текущее состояние клиентов' },
  { value: 'TRAINER_STATS', label: 'Статистика по тренерам' },
  { value: 'FUNNEL', label: 'Воронка продаж' },
  { value: 'FINANCIAL', label: 'Финансовый отчёт' },
];

const typeLabels: Record<string, string> = Object.fromEntries(
  REPORT_TYPES.map((t) => [t.value, t.label]),
);

const STATUS_CFG: Record<string, { label: string; variant: 'warning' | 'success' | 'default' | 'error' }> = {
  PENDING: { label: 'Ожидает', variant: 'warning' },
  GENERATING: { label: 'Генерируется', variant: 'warning' },
  COMPLETED: { label: 'Готов', variant: 'success' },
  FAILED: { label: 'Ошибка', variant: 'error' },
};

const STATUS_OPTIONS = [
  { value: '', label: 'Все статусы' },
  ...Object.entries(STATUS_CFG).map(([v, c]) => ({ value: v, label: c.label })),
];

const TYPE_FILTER_OPTIONS = [{ value: '', label: 'Все типы' }, ...REPORT_TYPES];

function toISO(d: Date): string {
  return d.toISOString().split('T')[0] ?? '';
}

function monthAgoISO(): string {
  const d = new Date();
  d.setMonth(d.getMonth() - 1);
  return toISO(d);
}

const dateInputCls =
  'flex h-10 w-full rounded-xl border border-[#E5E7EB] bg-white px-3 py-2 text-sm text-gray-900 focus:border-[#FF6B00] focus:outline-none focus:ring-2 focus:ring-[#FF6B00]/20';

export default function ReportsPage() {
  const [reports, setReports] = useState<Report[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [filterType, setFilterType] = useState('');
  const [filterStatus, setFilterStatus] = useState('');
  const [dialogOpen, setDialogOpen] = useState(false);
  const [genType, setGenType] = useState('CLIENT_STATUS');
  const [genDateFrom, setGenDateFrom] = useState(monthAgoISO);
  const [genDateTo, setGenDateTo] = useState(() => toISO(new Date()));
  const [generating, setGenerating] = useState(false);
  const [genError, setGenError] = useState<string | null>(null);

  const fetchReports = useCallback(() => {
    setLoading(true);
    setError(null);
    const params = new URLSearchParams({ limit: '50' });
    if (filterType) params.set('type', filterType);
    if (filterStatus) params.set('status', filterStatus);

    api
      .get<{ data: Report[]; hasMore: boolean; nextCursor: string | null }>(
        `/reports?${params.toString()}`,
      )
      .then((res) => setReports(res.data))
      .catch((err: unknown) => {
        setReports([]);
        setError(err instanceof ApiError ? err.message : 'Не удалось загрузить отчёты');
      })
      .finally(() => setLoading(false));
  }, [filterType, filterStatus]);

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

  // Poll while any report is still processing
  useEffect(() => {
    const hasPending = reports.some((r) => r.status === 'PENDING' || r.status === 'GENERATING');
    if (!hasPending) return;
    const id = setInterval(fetchReports, 10_000);
    return () => clearInterval(id);
  }, [reports, fetchReports]);

  const handleGenerate = () => {
    setGenerating(true);
    setGenError(null);
    api
      .post<Report>('/reports/generate', { type: genType, dateFrom: genDateFrom, dateTo: genDateTo })
      .then((r) => { setReports((prev) => [r, ...prev]); setDialogOpen(false); })
      .catch((err: unknown) => {
        setGenError(err instanceof ApiError ? err.message : 'Не удалось создать отчёт');
      })
      .finally(() => setGenerating(false));
  };

  const handleDownload = (r: Report) => {
    if (r.fileUrl) { window.open(r.fileUrl, '_blank'); return; }
    const base = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000/v1';
    window.open(`${base}/reports/${r.id}/download`, '_blank');
  };

  const completedCount = reports.filter((r) => r.status === 'COMPLETED').length;
  const pendingCount = reports.filter((r) => r.status === 'PENDING' || r.status === 'GENERATING').length;
  const failedCount = reports.filter((r) => r.status === 'FAILED').length;

  if (loading && reports.length === 0) {
    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>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold text-gray-900">Отчёты</h1>
        <div className="flex gap-2">
          <Button variant="outline" onClick={fetchReports} disabled={loading}>
            <RefreshCw className={`mr-2 h-4 w-4 ${loading ? 'animate-spin' : ''}`} />
            Обновить
          </Button>
          <Button onClick={() => setDialogOpen(true)}>
            <Plus className="mr-2 h-4 w-4" />
            Создать отчёт
          </Button>
        </div>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-4 gap-4">
        {[
          { label: 'Всего отчётов', value: reports.length, color: 'text-gray-900' },
          { label: 'Готово', value: completedCount, color: 'text-[#43A047]' },
          { label: 'В обработке', value: pendingCount, color: 'text-[#FF9800]' },
          { label: 'Ошибки', value: failedCount, color: 'text-[#E53935]' },
        ].map((s) => (
          <Card key={s.label}>
            <CardContent className="p-4">
              <p className="text-sm text-[#6B7280]">{s.label}</p>
              <p className={`text-2xl font-bold ${s.color}`}>{s.value}</p>
            </CardContent>
          </Card>
        ))}
      </div>

      {/* Error banner */}
      {error && (
        <div className="flex items-center gap-3 rounded-xl border border-[#E53935]/30 bg-[#E53935]/5 p-4">
          <AlertCircle className="h-5 w-5 shrink-0 text-[#E53935]" />
          <p className="text-sm text-[#E53935]">{error}</p>
        </div>
      )}

      {/* Filters */}
      <div className="flex gap-4">
        <div className="w-56">
          <Select options={TYPE_FILTER_OPTIONS} value={filterType}
            onChange={(e) => setFilterType(e.target.value)} />
        </div>
        <div className="w-56">
          <Select options={STATUS_OPTIONS} value={filterStatus}
            onChange={(e) => setFilterStatus(e.target.value)} />
        </div>
      </div>

      {/* Reports table */}
      <Card>
        <CardHeader>
          <CardTitle>Сгенерированные отчёты</CardTitle>
        </CardHeader>
        <CardContent>
          {reports.length === 0 ? (
            <p className="py-8 text-center text-[#6B7280]">
              Отчёты не найдены. Нажмите &laquo;Создать отчёт&raquo;, чтобы сгенерировать первый.
            </p>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead>
                  <tr className="border-b border-[#E5E7EB]">
                    {['Название', 'Тип', 'Автор', 'Дата', 'Статус', 'Действие'].map((h) => (
                      <th key={h} className="pb-3 text-left font-medium text-[#6B7280]">{h}</th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {reports.map((report) => {
                    const cfg = STATUS_CFG[report.status];
                    return (
                      <tr key={report.id} className="border-b border-[#E5E7EB] last:border-0">
                        <td className="py-3 font-medium text-gray-900">
                          <div className="flex items-center gap-2">
                            <FileText className="h-4 w-4 text-[#FF6B00]" />
                            {report.title}
                          </div>
                        </td>
                        <td className="py-3 text-[#6B7280]">
                          {typeLabels[report.type] ?? report.type}
                        </td>
                        <td className="py-3 text-[#6B7280]">
                          {report.generatedBy
                            ? `${report.generatedBy.lastName} ${report.generatedBy.firstName.charAt(0)}.`
                            : '\u2014'}
                        </td>
                        <td className="py-3 text-[#6B7280]">
                          {new Date(report.createdAt).toLocaleDateString('ru-RU')}
                        </td>
                        <td className="py-3">
                          <Badge variant={cfg?.variant ?? 'default'}>
                            {cfg?.label ?? report.status}
                          </Badge>
                        </td>
                        <td className="py-3">
                          {report.status === 'COMPLETED' && (
                            <Button variant="outline" size="sm" onClick={() => handleDownload(report)}>
                              <Download className="mr-1.5 h-3.5 w-3.5" />
                              PDF
                            </Button>
                          )}
                          {(report.status === 'PENDING' || report.status === 'GENERATING') && (
                            <span className="inline-flex items-center gap-1.5 text-xs text-[#FF9800]">
                              <RefreshCw className="h-3 w-3 animate-spin" />
                              Обработка...
                            </span>
                          )}
                          {report.status === 'FAILED' && (
                            <span className="text-xs text-[#E53935]">Ошибка генерации</span>
                          )}
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Generate Report Dialog */}
      <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Создать отчёт</DialogTitle>
            <DialogDescription>
              Выберите тип отчёта и период для генерации PDF-документа.
            </DialogDescription>
          </DialogHeader>
          <div className="mt-4 space-y-4">
            <Select label="Тип отчёта" options={REPORT_TYPES} value={genType}
              onChange={(e) => setGenType(e.target.value)} />
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="mb-1.5 block text-sm font-medium text-gray-700">Дата начала</label>
                <input type="date" value={genDateFrom} onChange={(e) => setGenDateFrom(e.target.value)}
                  className={dateInputCls} />
              </div>
              <div>
                <label className="mb-1.5 block text-sm font-medium text-gray-700">Дата окончания</label>
                <input type="date" value={genDateTo} onChange={(e) => setGenDateTo(e.target.value)}
                  className={dateInputCls} />
              </div>
            </div>
            {genError && (
              <div className="flex items-center gap-2 rounded-lg bg-[#E53935]/5 p-3">
                <AlertCircle className="h-4 w-4 shrink-0 text-[#E53935]" />
                <p className="text-sm text-[#E53935]">{genError}</p>
              </div>
            )}
          </div>
          <DialogFooter className="mt-6">
            <Button variant="outline" onClick={() => setDialogOpen(false)} disabled={generating}>
              Отмена
            </Button>
            <Button onClick={handleGenerate} disabled={generating}>
              {generating
                ? <><RefreshCw className="mr-2 h-4 w-4 animate-spin" />Генерация...</>
                : <><FileText className="mr-2 h-4 w-4" />Сгенерировать</>}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
