'use client'

import { useState, useEffect } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { usePayments } from '@/contexts/PaymentsContext'
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts'
import { TrendingUp, RefreshCw } from 'lucide-react'

const formatDate = (iso: string) =>
  new Date(iso).toLocaleDateString('fr-FR', { month: 'short', day: 'numeric' })

const STATUS_COLORS = {
  success:  'bg-emerald-50 text-emerald-700 ring-1 ring-inset ring-emerald-200',
  failed:   'bg-red-50    text-red-700    ring-1 ring-inset ring-red-200',
  refunded: 'bg-amber-50  text-amber-700  ring-1 ring-inset ring-amber-200',
}

export function PaymentChart() {
  const { trends, trendsLoading, trendsError, fetchTrends } = usePayments()
  const [period, setPeriod] = useState('7days')

  useEffect(() => { fetchTrends(period) }, [period, fetchTrends])

  const pct = (n: number) =>
    trends?.total ? `${Math.round((n / trends.total) * 100)}%` : '—'

  return (
    <Card className="border border-gray-200 shadow-none bg-white flex flex-col h-full">
      <CardHeader className="px-5 py-4 border-b border-gray-100">
        <div className="flex items-center justify-between">
          <div>
            <CardTitle className="text-sm font-semibold text-gray-800 flex items-center gap-2">
              <TrendingUp className="w-4 h-4 text-rose-500" />
              Tendances
            </CardTitle>
            <p className="text-[11px] text-gray-400 mt-0.5">Transactions par période</p>
          </div>
          <Select value={period} onValueChange={setPeriod}>
            <SelectTrigger className="h-7 w-[120px] border-gray-200 text-xs rounded-lg">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="7days">7 jours</SelectItem>
              <SelectItem value="30days">30 jours</SelectItem>
              <SelectItem value="90days">3 mois</SelectItem>
              <SelectItem value="year">Cette année</SelectItem>
            </SelectContent>
          </Select>
        </div>
      </CardHeader>

      <CardContent className="p-5 space-y-4 flex-1">
        <div className="h-[180px] rounded-xl overflow-hidden">
          {trendsLoading || !trends?.byDay ? (
            <div className="h-full flex items-center justify-center text-gray-400">
              <div className="text-center">
                <RefreshCw className="h-5 w-5 animate-spin mx-auto mb-2" />
                <p className="text-xs">Chargement…</p>
              </div>
            </div>
          ) : (
            <ResponsiveContainer width="100%" height="100%">
              <LineChart data={trends.byDay} margin={{ left: 0, right: 8, top: 8, bottom: 0 }}>
                <CartesianGrid stroke="#f0f0f0" strokeDasharray="3 3" vertical={false} />
                <XAxis
                  dataKey="date"
                  tickFormatter={formatDate}
                  axisLine={false}
                  tickLine={false}
                  fontSize={10}
                  tick={{ fill: '#9ca3af' }}
                />
                <YAxis
                  allowDecimals={false}
                  axisLine={false}
                  tickLine={false}
                  fontSize={10}
                  tick={{ fill: '#9ca3af' }}
                  width={28}
                />
                <Tooltip
                  formatter={(v: number) => [`${v} paiements`]}
                  labelFormatter={(l: string) => formatDate(l)}
                  contentStyle={{
                    background: '#fff',
                    border: '1px solid #e5e7eb',
                    borderRadius: '8px',
                    fontSize: 12,
                    boxShadow: '0 4px 6px -1px rgb(0 0 0 / 0.05)',
                  }}
                  cursor={{ stroke: '#e5e7eb' }}
                />
                <Line
                  type="monotone"
                  dataKey="count"
                  stroke="#e11d48"
                  strokeWidth={2}
                  dot={false}
                  activeDot={{ r: 4, fill: '#e11d48', stroke: '#fff', strokeWidth: 2 }}
                />
              </LineChart>
            </ResponsiveContainer>
          )}
        </div>

        {trendsError && (
          <p className="text-xs text-red-500">{trendsError}</p>
        )}

        <div className="grid grid-cols-3 gap-2">
          {(['success', 'failed', 'refunded'] as const).map((key) => (
            <div key={key} className={`rounded-lg p-3 ${STATUS_COLORS[key]}`}>
              <p className="text-[10px] font-medium mb-1 capitalize">
                {key === 'success' ? 'Réussis' : key === 'failed' ? 'Échoués' : 'Remboursés'}
              </p>
              <p className="text-lg font-bold tabular-nums">
                {trendsLoading || !trends ? '…' : pct(trends[key as keyof typeof trends] as number)}
              </p>
            </div>
          ))}
        </div>
      </CardContent>
    </Card>
  )
}
