/**
 * ReportsPage – Dashboard e Reportistica (Fase 7).
 *
 * Visualizza:
 * - 6 KPI cards (ricevute oggi, inviate oggi, anomalie, tasso consegna,
 *               caselle in errore, messaggi non letti)
 * - Selettore periodo (7 / 30 giorni)
 * - Grafico a barre: PEC ricevute vs inviate per giorno
 * - Grafico a torta: distribuzione stati messaggi outbound
 * - Tabella: dettaglio per casella
 * - Pulsanti export CSV e PDF
 */

import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  PieChart,
  Pie,
  Cell,
  ResponsiveContainer,
} from 'recharts'
import {
  Inbox,
  Send,
  AlertTriangle,
  CheckCircle2,
  ServerCrash,
  MailOpen,
  Download,
  FileText,
  RefreshCw,
  BarChart2,
} from 'lucide-react'
import { format, parseISO } from 'date-fns'
import { it } from 'date-fns/locale'
import { reportsApi } from '@/api/reports.api'
import { cn } from '@/lib/utils'

// ─── Costanti ─────────────────────────────────────────────────────────────────

const PERIOD_OPTIONS = [
  { label: '7 giorni', value: 7 },
  { label: '30 giorni', value: 30 },
  { label: '90 giorni', value: 90 },
]

const STATE_COLORS: Record<string, string> = {
  delivered:         '#22c55e',
  accepted:          '#3b82f6',
  sent:              '#8b5cf6',
  anomaly:           '#ef4444',
  failed:            '#dc2626',
  queued:            '#f59e0b',
  draft:             '#6b7280',
  unknown:           '#9ca3af',
}

const STATE_LABELS: Record<string, string> = {
  delivered:         'Consegnata',
  accepted:          'Accettata',
  sent:              'Inviata',
  anomaly:           'Anomalia',
  failed:            'Fallita',
  queued:            'In coda',
  draft:             'Bozza',
  unknown:           'Sconosciuto',
}

const STATUS_BADGE: Record<string, string> = {
  active:  'bg-green-100 text-green-800',
  paused:  'bg-yellow-100 text-yellow-800',
  error:   'bg-red-100 text-red-800',
  deleted: 'bg-gray-100 text-gray-600',
}

// ─── Componente KPI card ──────────────────────────────────────────────────────

interface KpiCardProps {
  title: string
  value: string | number
  subtitle?: string
  icon: React.ReactNode
  color: string
  alert?: boolean
}

function KpiCard({ title, value, subtitle, icon, color, alert }: KpiCardProps) {
  return (
    <div
      className={cn(
        'bg-white rounded-xl border p-5 flex items-start gap-4',
        alert && 'border-red-300 bg-red-50',
      )}
    >
      <div className={cn('p-2.5 rounded-lg flex-shrink-0', color)}>
        {icon}
      </div>
      <div className="min-w-0">
        <p className="text-sm text-gray-500 font-medium truncate">{title}</p>
        <p className={cn('text-2xl font-bold mt-0.5', alert ? 'text-red-700' : 'text-gray-900')}>
          {value}
        </p>
        {subtitle && (
          <p className="text-xs text-gray-400 mt-0.5">{subtitle}</p>
        )}
      </div>
    </div>
  )
}

// ─── Tooltip grafico barre ────────────────────────────────────────────────────

function CustomBarTooltip({ active, payload, label }: any) {
  if (!active || !payload?.length) return null
  return (
    <div className="bg-white border rounded-lg shadow-lg p-3 text-sm">
      <p className="font-semibold text-gray-700 mb-1">{label}</p>
      {payload.map((p: any) => (
        <p key={p.dataKey} style={{ color: p.fill }}>
          {p.name}: <strong>{p.value}</strong>
        </p>
      ))}
    </div>
  )
}

// ─── Tooltip grafico torta ────────────────────────────────────────────────────

function CustomPieTooltip({ active, payload }: any) {
  if (!active || !payload?.length) return null
  const item = payload[0]
  return (
    <div className="bg-white border rounded-lg shadow-lg p-3 text-sm">
      <p className="font-semibold" style={{ color: item.payload.fill }}>
        {STATE_LABELS[item.name] ?? item.name}
      </p>
      <p className="text-gray-700">Totale: <strong>{item.value}</strong></p>
    </div>
  )
}

// ─── Pagina principale ────────────────────────────────────────────────────────

export function ReportsPage() {
  const [days, setDays] = useState(7)

  const { data, isLoading, isError, refetch, isFetching } = useQuery({
    queryKey: ['reports-summary', days],
    queryFn: () => reportsApi.getSummary(days),
    staleTime: 2 * 60 * 1000,
    refetchOnWindowFocus: false,
  })

  // ── Formatta le date per l'asse X del grafico ────────────────────────────
  const chartData = (data?.daily_stats ?? []).map((s) => ({
    giorno: format(parseISO(s.day), 'dd/MM', { locale: it }),
    Ricevute: s.received,
    Inviate: s.sent,
  }))

  const pieData = (data?.outbound_states ?? [])
    .filter((s) => s.count > 0)
    .map((s) => ({
      name: s.state,
      value: s.count,
      fill: STATE_COLORS[s.state] ?? '#9ca3af',
    }))

  const kpi = data?.kpi
  const generatedAt = data?.generated_at
    ? format(parseISO(data.generated_at), "dd/MM/yyyy HH:mm", { locale: it })
    : null

  // ── URL export con token auth (il browser apre con i cookie di sessione) ──
  const handleExport = (format: 'csv' | 'pdf') => {
    const url = format === 'csv'
      ? reportsApi.exportCsv()
      : reportsApi.exportPdf()

    // Apre il link in una nuova scheda; il token JWT viene inviato
    // automaticamente grazie all'interceptor axios, ma per i download
    // diretti usiamo fetch con il token dallo store.
    const token = localStorage.getItem('access_token')
    if (!token) {
      window.open(url, '_blank')
      return
    }
    fetch(url, { headers: { Authorization: `Bearer ${token}` } })
      .then((res) => {
        if (!res.ok) throw new Error('Errore download')
        return res.blob()
      })
      .then((blob) => {
        const ext = format === 'csv' ? 'csv' : 'pdf'
        const ts = new Date().toISOString().slice(0, 16).replace('T', '_').replace(':', '')
        const filename = `pechub_report_${ts}.${ext}`
        const a = document.createElement('a')
        a.href = URL.createObjectURL(blob)
        a.download = filename
        a.click()
        URL.revokeObjectURL(a.href)
      })
      .catch(() => alert('Errore durante il download del report'))
  }

  // ─────────────────────────────────────────────────────────────────────────

  return (
    <div className="flex flex-col h-full overflow-y-auto bg-gray-50">
      {/* ── Intestazione ── */}
      <div className="sticky top-0 z-10 bg-white border-b px-6 py-4 flex flex-col sm:flex-row sm:items-center gap-3">
        <div className="flex items-center gap-3 flex-1 min-w-0">
          <BarChart2 className="h-6 w-6 text-blue-600 flex-shrink-0" />
          <div className="min-w-0">
            <h1 className="text-xl font-bold text-gray-900">Dashboard</h1>
            {generatedAt && (
              <p className="text-xs text-gray-400">Aggiornato il {generatedAt}</p>
            )}
          </div>
        </div>

        <div className="flex items-center gap-2 flex-shrink-0">
          {/* Selettore periodo */}
          <div className="flex rounded-lg border bg-white overflow-hidden text-sm">
            {PERIOD_OPTIONS.map((opt) => (
              <button
                key={opt.value}
                onClick={() => setDays(opt.value)}
                className={cn(
                  'px-3 py-1.5 font-medium transition-colors',
                  days === opt.value
                    ? 'bg-blue-600 text-white'
                    : 'text-gray-600 hover:bg-gray-50',
                )}
              >
                {opt.label}
              </button>
            ))}
          </div>

          {/* Aggiorna */}
          <button
            onClick={() => refetch()}
            disabled={isFetching}
            className="p-2 rounded-lg border bg-white text-gray-600 hover:bg-gray-50 disabled:opacity-50 transition-colors"
            title="Aggiorna dati"
          >
            <RefreshCw className={cn('h-4 w-4', isFetching && 'animate-spin')} />
          </button>

          {/* Export CSV */}
          <button
            onClick={() => handleExport('csv')}
            className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg border bg-white text-sm text-gray-700 hover:bg-gray-50 transition-colors"
          >
            <Download className="h-4 w-4" />
            CSV
          </button>

          {/* Export PDF */}
          <button
            onClick={() => handleExport('pdf')}
            className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg border bg-white text-sm text-gray-700 hover:bg-gray-50 transition-colors"
          >
            <FileText className="h-4 w-4" />
            PDF
          </button>
        </div>
      </div>

      {/* ── Contenuto ── */}
      <div className="flex-1 p-6 space-y-6 max-w-7xl mx-auto w-full">

        {/* ── Loading / Errore ── */}
        {isLoading && (
          <div className="flex items-center justify-center h-64 text-gray-500">
            <RefreshCw className="h-6 w-6 animate-spin mr-2" />
            Caricamento dati...
          </div>
        )}

        {isError && (
          <div className="bg-red-50 border border-red-200 rounded-xl p-6 text-center text-red-700">
            Errore nel caricamento dei dati. Riprova.
          </div>
        )}

        {data && (
          <>
            {/* ── Riga KPI ── */}
            <div className="grid grid-cols-2 md:grid-cols-3 xl:grid-cols-6 gap-4">
              <KpiCard
                title="Ricevute oggi"
                value={kpi!.received_today}
                subtitle={`${kpi!.received_7d} negli ultimi 7gg`}
                icon={<Inbox className="h-5 w-5 text-blue-600" />}
                color="bg-blue-50"
              />
              <KpiCard
                title="Inviate oggi"
                value={kpi!.sent_today}
                subtitle={`${kpi!.sent_7d} negli ultimi 7gg`}
                icon={<Send className="h-5 w-5 text-indigo-600" />}
                color="bg-indigo-50"
              />
              <KpiCard
                title="Anomalie attive"
                value={kpi!.anomalie_attive}
                icon={<AlertTriangle className="h-5 w-5 text-orange-600" />}
                color="bg-orange-50"
                alert={kpi!.anomalie_attive > 0}
              />
              <KpiCard
                title="Tasso consegna"
                value={`${kpi!.tasso_consegna}%`}
                icon={<CheckCircle2 className="h-5 w-5 text-green-600" />}
                color="bg-green-50"
              />
              <KpiCard
                title="Caselle in errore"
                value={kpi!.caselle_in_errore}
                icon={<ServerCrash className="h-5 w-5 text-red-600" />}
                color="bg-red-50"
                alert={kpi!.caselle_in_errore > 0}
              />
              <KpiCard
                title="Non letti"
                value={kpi!.messaggi_non_letti}
                icon={<MailOpen className="h-5 w-5 text-purple-600" />}
                color="bg-purple-50"
              />
            </div>

            {/* ── Grafici ── */}
            <div className="grid grid-cols-1 xl:grid-cols-3 gap-6">

              {/* Grafico a barre (2/3) */}
              <div className="xl:col-span-2 bg-white rounded-xl border p-5">
                <h2 className="text-base font-semibold text-gray-800 mb-4">
                  Attivita PEC – ultimi {days} giorni
                </h2>
                {chartData.length === 0 ? (
                  <div className="h-52 flex items-center justify-center text-gray-400 text-sm">
                    Nessun dato nel periodo selezionato
                  </div>
                ) : (
                  <ResponsiveContainer width="100%" height={220}>
                    <BarChart
                      data={chartData}
                      margin={{ top: 4, right: 12, left: 0, bottom: 0 }}
                    >
                      <CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" />
                      <XAxis
                        dataKey="giorno"
                        tick={{ fontSize: 11, fill: '#6b7280' }}
                        tickLine={false}
                        axisLine={false}
                      />
                      <YAxis
                        tick={{ fontSize: 11, fill: '#6b7280' }}
                        tickLine={false}
                        axisLine={false}
                        allowDecimals={false}
                      />
                      <Tooltip content={<CustomBarTooltip />} />
                      <Legend
                        wrapperStyle={{ fontSize: 12, paddingTop: 8 }}
                      />
                      <Bar
                        dataKey="Ricevute"
                        fill="#3b82f6"
                        radius={[3, 3, 0, 0]}
                        maxBarSize={24}
                      />
                      <Bar
                        dataKey="Inviate"
                        fill="#8b5cf6"
                        radius={[3, 3, 0, 0]}
                        maxBarSize={24}
                      />
                    </BarChart>
                  </ResponsiveContainer>
                )}
              </div>

              {/* Grafico a torta (1/3) */}
              <div className="bg-white rounded-xl border p-5">
                <h2 className="text-base font-semibold text-gray-800 mb-4">
                  Stato messaggi outbound
                </h2>
                {pieData.length === 0 ? (
                  <div className="h-52 flex items-center justify-center text-gray-400 text-sm">
                    Nessun messaggio outbound
                  </div>
                ) : (
                  <>
                    <ResponsiveContainer width="100%" height={160}>
                      <PieChart>
                        <Pie
                          data={pieData}
                          cx="50%"
                          cy="50%"
                          innerRadius={45}
                          outerRadius={72}
                          paddingAngle={2}
                          dataKey="value"
                        >
                          {pieData.map((entry, index) => (
                            <Cell key={index} fill={entry.fill} />
                          ))}
                        </Pie>
                        <Tooltip content={<CustomPieTooltip />} />
                      </PieChart>
                    </ResponsiveContainer>
                    {/* Legenda manuale */}
                    <div className="mt-2 space-y-1">
                      {pieData.map((entry) => (
                        <div key={entry.name} className="flex items-center justify-between text-xs">
                          <div className="flex items-center gap-1.5">
                            <span
                              className="inline-block h-2.5 w-2.5 rounded-full flex-shrink-0"
                              style={{ backgroundColor: entry.fill }}
                            />
                            <span className="text-gray-600">
                              {STATE_LABELS[entry.name] ?? entry.name}
                            </span>
                          </div>
                          <span className="font-semibold text-gray-800">{entry.value}</span>
                        </div>
                      ))}
                    </div>
                  </>
                )}
              </div>
            </div>

            {/* ── Tabella caselle ── */}
            {data.mailbox_stats.length > 0 && (
              <div className="bg-white rounded-xl border">
                <div className="px-5 py-4 border-b">
                  <h2 className="text-base font-semibold text-gray-800">
                    Dettaglio per casella
                  </h2>
                </div>
                <div className="overflow-x-auto">
                  <table className="w-full text-sm">
                    <thead>
                      <tr className="bg-gray-50 border-b">
                        <th className="text-left px-5 py-3 font-semibold text-gray-600">Casella</th>
                        <th className="text-center px-4 py-3 font-semibold text-gray-600">Stato</th>
                        <th className="text-right px-4 py-3 font-semibold text-gray-600">Ricevute</th>
                        <th className="text-right px-4 py-3 font-semibold text-gray-600">Inviate</th>
                        <th className="text-right px-4 py-3 font-semibold text-gray-600">Anomalie</th>
                        <th className="text-right px-4 py-3 font-semibold text-gray-600">Non letti</th>
                        <th className="text-right px-5 py-3 font-semibold text-gray-600">Ultima sync</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-gray-100">
                      {data.mailbox_stats.map((mb) => (
                        <tr key={mb.mailbox_id} className="hover:bg-gray-50 transition-colors">
                          <td className="px-5 py-3">
                            <div className="font-medium text-gray-900 truncate max-w-xs">
                              {mb.display_name || mb.email_address}
                            </div>
                            {mb.display_name && (
                              <div className="text-xs text-gray-400">{mb.email_address}</div>
                            )}
                          </td>
                          <td className="px-4 py-3 text-center">
                            <span
                              className={cn(
                                'inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium',
                                STATUS_BADGE[mb.status] ?? 'bg-gray-100 text-gray-600',
                              )}
                            >
                              {mb.status}
                            </span>
                          </td>
                          <td className="px-4 py-3 text-right font-medium text-gray-900">
                            {mb.received_total}
                          </td>
                          <td className="px-4 py-3 text-right font-medium text-gray-900">
                            {mb.sent_total}
                          </td>
                          <td className="px-4 py-3 text-right">
                            {mb.anomalie > 0 ? (
                              <span className="font-semibold text-red-600">{mb.anomalie}</span>
                            ) : (
                              <span className="text-gray-400">0</span>
                            )}
                          </td>
                          <td className="px-4 py-3 text-right">
                            {mb.non_letti > 0 ? (
                              <span className="font-semibold text-blue-600">{mb.non_letti}</span>
                            ) : (
                              <span className="text-gray-400">0</span>
                            )}
                          </td>
                          <td className="px-5 py-3 text-right text-gray-500 text-xs">
                            {mb.last_sync_at
                              ? format(parseISO(mb.last_sync_at), 'dd/MM HH:mm', { locale: it })
                              : '—'}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>
            )}

            {/* Footer */}
            <p className="text-xs text-gray-400 text-center pb-2">
              Totale messaggi nel sistema: {kpi!.totale_messaggi.toLocaleString('it-IT')}
            </p>
          </>
        )}
      </div>
    </div>
  )
}
