'use client'

import { useEffect, useMemo, useState } from 'react'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog'
import { Badge } from '@/components/ui/badge'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Input } from '@/components/ui/input'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import { Button } from '@/components/ui/button'
import { Skeleton } from '@/components/ui/skeleton'
import { ConfirmDialog } from '@/components/ui/confirm-dialog'
import {
  getInfluencerDetails, getInfluencerUsages,
  recordInfluencerPayout, updateInfluencer, deleteInfluencer,
  AdminInfluencerDetailResponse, AdminUsageListResponse,
} from '@/lib/influencers'
import { toast } from 'sonner'
import {
  Activity, RefreshCw, Search, Users, Wallet, Mail, Phone,
  Calendar, TrendingUp, CreditCard, Trash2, Send, AlertCircle,
} from 'lucide-react'
import { formatDistanceToNow } from 'date-fns'
import { fr } from 'date-fns/locale'
import { cn } from '@/lib/utils'

const formatCurrency = (value: number = 0) =>
  new Intl.NumberFormat('fr-FR', { style: 'currency', currency: 'XOF', maximumFractionDigits: 0 }).format(value || 0)

const formatDateDistance = (value?: string | null) => {
  if (!value) return '—'
  try { return formatDistanceToNow(new Date(value), { locale: fr, addSuffix: true }) }
  catch { return '—' }
}

export function InfluencerDetailsDialog({
  influencerId, open, onOpenChange, onUpdated, onDeleted,
}: {
  influencerId: number | null
  open: boolean
  onOpenChange: (val: boolean) => void
  onUpdated?: () => void
  onDeleted?: () => void
}) {
  const [details, setDetails]           = useState<AdminInfluencerDetailResponse | null>(null)
  const [loading, setLoading]           = useState(false)
  const [history, setHistory]           = useState<AdminUsageListResponse | null>(null)
  const [historyLoading, setHistoryLoading] = useState(false)
  const [historyPage, setHistoryPage]   = useState(1)
  const [historySearch, setHistorySearch] = useState('')
  const [historyQuery, setHistoryQuery] = useState('')
  const [activeTab, setActiveTab]       = useState<'overview' | 'history'>('overview')
  const [fetchError, setFetchError]     = useState<string | null>(null)
  const [payoutAmount, setPayoutAmount] = useState('')
  const [payoutLoading, setPayoutLoading] = useState(false)
  const [payoutError, setPayoutError]   = useState<string | null>(null)
  const [deleteOpen, setDeleteOpen]     = useState(false)
  const [deleteLoading, setDeleteLoading] = useState(false)
  const [rateInput, setRateInput]       = useState('')
  const [rateLoading, setRateLoading]   = useState(false)
  const [rateError, setRateError]       = useState<string | null>(null)

  useEffect(() => {
    const t = setTimeout(() => { setHistoryQuery(historySearch.trim()); setHistoryPage(1) }, 400)
    return () => clearTimeout(t)
  }, [historySearch])

  useEffect(() => {
    if (open && influencerId) { setFetchError(null); fetchDetails(influencerId) }
    if (!open) { setDetails(null); setFetchError(null) }
  }, [open, influencerId])

  useEffect(() => {
    if (details) setRateInput(String(details.data.payoutPerSignup ?? ''))
  }, [details])

  useEffect(() => {
    if (open && influencerId && activeTab === 'history') fetchHistory(influencerId)
  }, [open, influencerId, activeTab, historyPage, historyQuery])

  const fetchDetails = async (id: number) => {
    try {
      setLoading(true)
      setDetails(await getInfluencerDetails(id))
    } catch (err) {
      const e = err as { response?: { data?: { message?: string } } }
      setFetchError(e?.response?.data?.message || 'Impossible de charger les détails')
    } finally {
      setLoading(false)
    }
  }

  const fetchHistory = async (id: number) => {
    try {
      setHistoryLoading(true)
      setHistory(await getInfluencerUsages(id, { page: historyPage, q: historyQuery }))
    } catch {
      toast.error('Historique indisponible')
    } finally {
      setHistoryLoading(false)
    }
  }

  const handlePayout = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!influencerId) return
    const amount = Number(payoutAmount)
    if (!Number.isFinite(amount) || amount <= 0) {
      setPayoutError('Entrez un montant valide supérieur à zéro.')
      return
    }
    try {
      setPayoutLoading(true)
      setPayoutError(null)
      await recordInfluencerPayout(influencerId, amount)
      toast.success('Paiement enregistré avec succès')
      setPayoutAmount('')
      await fetchDetails(influencerId)
      if (activeTab === 'history') await fetchHistory(influencerId)
      onUpdated?.()
    } catch {
      setPayoutError('Impossible de valider le paiement. Veuillez réessayer.')
    } finally {
      setPayoutLoading(false)
    }
  }

  const handleRateChange = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!influencerId) return
    const amount = Number(rateInput)
    if (!Number.isFinite(amount) || amount <= 0) {
      setRateError("Entrez un montant valide supérieur à zéro, sinon l'influenceur ne gagnera rien.")
      return
    }
    try {
      setRateLoading(true)
      setRateError(null)
      await updateInfluencer(influencerId, { payoutPerSignup: amount })
      toast.success('Gain par inscription mis à jour')
      await fetchDetails(influencerId)
      onUpdated?.()
    } catch {
      setRateError('Impossible de mettre à jour ce montant. Veuillez réessayer.')
    } finally {
      setRateLoading(false)
    }
  }

  const handleDelete = async () => {
    if (!influencerId) return
    try {
      setDeleteLoading(true)
      await deleteInfluencer(influencerId)
      toast.success('Influenceur supprimé')
      onDeleted?.()
      onOpenChange(false)
    } catch {
      toast.error('Impossible de supprimer cet influenceur')
    } finally {
      setDeleteLoading(false)
    }
  }

  const stats = useMemo(() => {
    if (!details) return []
    const totalUses = details.stats.totalUses ?? details.stats.totalSignups ?? 0
    const avgCommission = totalUses > 0 ? details.stats.totalEarned / totalUses : 0
    return [
      { label: 'Utilisations', value: totalUses.toLocaleString('fr-FR'), icon: Users,      caption: 'Depuis la création du code', color: 'text-blue-600',   bg: 'bg-blue-50'   },
      { label: 'Gains cumulés', value: formatCurrency(details.stats.totalEarned), icon: Wallet,     caption: `${formatCurrency(avgCommission)} / paiement`, color: 'text-emerald-600', bg: 'bg-emerald-50' },
      { label: 'Solde estimé',  value: formatCurrency(details.stats.balance), icon: CreditCard, caption: `Versé : ${formatCurrency(details.data.totalPaid)}`, color: 'text-rose-600',    bg: 'bg-rose-50'   },
      { label: 'Dernière activité', value: formatDateDistance(details.stats.lastUsageAt), icon: Activity,  caption: details.stats.lastUsageAt ? 'Code actif' : 'Aucune utilisation', color: 'text-amber-600',  bg: 'bg-amber-50'  },
    ]
  }, [details])

  const isActive = details?.data.status !== 'inactive'

  return (
    <>
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">

          {/* Header */}
          <DialogHeader className="pb-4 border-b border-gray-100">
            <div className="space-y-2">
              {loading ? (
                <Skeleton className="h-5 w-32" />
              ) : (
                <div className="flex items-center gap-2">
                  <Badge variant="outline" className="font-mono text-xs bg-gray-50 text-gray-600">
                    #{details?.data.promoCode || '—'}
                  </Badge>
                  <span className={cn(
                    'inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-medium',
                    isActive
                      ? 'bg-emerald-50 text-emerald-700 ring-1 ring-inset ring-emerald-200'
                      : 'bg-gray-100 text-gray-500 ring-1 ring-inset ring-gray-200'
                  )}>
                    {isActive ? 'Actif' : 'Inactif'}
                  </span>
                </div>
              )}
              <DialogTitle className="text-xl font-bold text-gray-900">
                {loading
                  ? <Skeleton className="h-7 w-48" />
                  : details
                    ? `${details.data.user.firstName} ${details.data.user.lastName}`
                    : 'Détails influenceur'}
              </DialogTitle>
              <DialogDescription asChild>
                <div className="flex flex-wrap gap-3 text-sm text-gray-400">
                  {loading ? (
                    <Skeleton className="h-4 w-64" />
                  ) : (
                    <>
                      {details?.data.user.email && (
                        <span className="flex items-center gap-1">
                          <Mail className="w-3.5 h-3.5" /> {details.data.user.email}
                        </span>
                      )}
                      {details?.data.user.phone && (
                        <span className="flex items-center gap-1">
                          <Phone className="w-3.5 h-3.5" /> {details.data.user.phone}
                        </span>
                      )}
                    </>
                  )}
                </div>
              </DialogDescription>
            </div>
          </DialogHeader>

          {fetchError && (
            <div className="flex items-start gap-2.5 bg-red-50 border border-red-100 rounded-lg px-3 py-2.5 mt-2">
              <AlertCircle className="w-4 h-4 text-red-500 mt-0.5 flex-shrink-0" />
              <p className="text-sm text-red-600">{fetchError}</p>
            </div>
          )}

          <Tabs value={activeTab} onValueChange={v => setActiveTab(v as typeof activeTab)} className="mt-4">
            <TabsList className="grid w-full grid-cols-2 bg-gray-100 p-1 rounded-lg">
              <TabsTrigger value="overview" className="data-[state=active]:bg-white data-[state=active]:shadow-sm rounded-md text-sm">Aperçu</TabsTrigger>
              <TabsTrigger value="history"  className="data-[state=active]:bg-white data-[state=active]:shadow-sm rounded-md text-sm">Historique</TabsTrigger>
            </TabsList>

            {/* ── Overview ── */}
            <TabsContent value="overview" className="mt-5 space-y-5">

              {/* KPI grid */}
              <div className="grid gap-3 sm:grid-cols-2">
                {loading
                  ? Array.from({ length: 4 }).map((_, i) => (
                      <Card key={i} className="border border-gray-200 shadow-none">
                        <CardContent className="p-4 space-y-2">
                          <Skeleton className="h-3.5 w-24" />
                          <Skeleton className="h-6 w-32" />
                          <Skeleton className="h-3 w-20" />
                        </CardContent>
                      </Card>
                    ))
                  : stats.map(s => (
                      <Card key={s.label} className="border border-gray-200 shadow-none">
                        <CardContent className="p-4">
                          <div className="flex items-center justify-between mb-2">
                            <p className="text-xs font-medium text-gray-500">{s.label}</p>
                            <div className={cn('w-7 h-7 rounded-lg flex items-center justify-center', s.bg)}>
                              <s.icon className={cn('w-3.5 h-3.5', s.color)} />
                            </div>
                          </div>
                          <p className="text-xl font-bold text-gray-900 tabular-nums">{s.value}</p>
                          <p className="text-[11px] text-gray-400 mt-0.5">{s.caption}</p>
                        </CardContent>
                      </Card>
                    ))
                }
              </div>

              {details && (
                <div className="grid gap-4 lg:grid-cols-2">

                  {/* Infos complémentaires */}
                  <Card className="border border-gray-200 shadow-none">
                    <CardHeader className="px-5 py-4 border-b border-gray-100">
                      <CardTitle className="text-sm font-semibold text-gray-800 flex items-center gap-2">
                        <TrendingUp className="w-4 h-4 text-rose-500" />
                        Informations
                      </CardTitle>
                    </CardHeader>
                    <CardContent className="p-5 space-y-3">
                      <div className="flex justify-between items-center py-2 border-b border-gray-100">
                        <span className="text-xs text-gray-500">Gain par inscription</span>
                        <span className={cn(
                          'text-sm font-semibold',
                          details.data.payoutPerSignup > 0 ? 'text-gray-900' : 'text-rose-600'
                        )}>
                          {formatCurrency(details.data.payoutPerSignup)}
                          {details.data.payoutPerSignup <= 0 && ' · aucun gain !'}
                        </span>
                      </div>
                      <div className="flex justify-between items-center py-2 border-b border-gray-100">
                        <span className="text-xs text-gray-500">Commission moyenne</span>
                        <span className="text-sm font-semibold text-gray-900">
                          {formatCurrency(
                            (details.stats.totalUses ?? details.stats.totalSignups ?? 0) > 0
                              ? details.stats.totalEarned / (details.stats.totalUses ?? details.stats.totalSignups!)
                              : 0
                          )} / paiement
                        </span>
                      </div>
                      <div className="flex justify-between items-center py-2 border-b border-gray-100">
                        <span className="text-xs text-gray-500">Profil social</span>
                        <span className="text-sm text-gray-700">{details.data.socialHandle || '—'}</span>
                      </div>
                      <div className="py-2">
                        <p className="text-xs text-gray-500 mb-1.5">Notes</p>
                        <p className="text-sm text-gray-700 bg-gray-50 rounded-lg p-3">
                          {details.data.notes || 'Aucune note'}
                        </p>
                      </div>
                    </CardContent>
                  </Card>

                  {/* Actions admin */}
                  <Card className="border border-gray-200 shadow-none">
                    <CardHeader className="px-5 py-4 border-b border-gray-100">
                      <CardTitle className="text-sm font-semibold text-gray-800 flex items-center gap-2">
                        <Wallet className="w-4 h-4 text-rose-500" />
                        Actions admin
                      </CardTitle>
                    </CardHeader>
                    <CardContent className="p-5 space-y-4">
                      <form onSubmit={handleRateChange} className="space-y-3">
                        <p className="text-xs font-medium text-gray-700">Gain par inscription</p>
                        {rateError && (
                          <div className="flex items-start gap-2 bg-red-50 border border-red-100 rounded-lg px-3 py-2">
                            <AlertCircle className="w-3.5 h-3.5 text-red-500 mt-0.5 flex-shrink-0" />
                            <p className="text-xs text-red-600">{rateError}</p>
                          </div>
                        )}
                        <div className="flex gap-2">
                          <Input
                            type="number"
                            step="100"
                            min="0"
                            placeholder="Montant (F CFA)"
                            value={rateInput}
                            onChange={e => { setRateInput(e.target.value); setRateError(null) }}
                            className="flex-1 h-9 text-sm border-gray-200"
                          />
                          <Button
                            type="submit"
                            disabled={rateLoading}
                            size="sm"
                            className="bg-gray-900 hover:bg-gray-800 text-white gap-1.5 h-9"
                          >
                            {rateLoading
                              ? <RefreshCw className="w-3.5 h-3.5 animate-spin" />
                              : <Send className="w-3.5 h-3.5" />
                            }
                            Modifier
                          </Button>
                        </div>
                        <p className="text-[11px] text-gray-400">
                          Montant crédité à l'influenceur à chaque nouvelle inscription avec son code promo.
                        </p>
                      </form>

                      <form onSubmit={handlePayout} className="space-y-3 pt-3 border-t border-gray-100">
                        <p className="text-xs font-medium text-gray-700">Enregistrer un paiement</p>
                        {payoutError && (
                          <div className="flex items-start gap-2 bg-red-50 border border-red-100 rounded-lg px-3 py-2">
                            <AlertCircle className="w-3.5 h-3.5 text-red-500 mt-0.5 flex-shrink-0" />
                            <p className="text-xs text-red-600">{payoutError}</p>
                          </div>
                        )}
                        <div className="flex gap-2">
                          <Input
                            type="number"
                            step="100"
                            min="0"
                            placeholder="Montant (F CFA)"
                            value={payoutAmount}
                            onChange={e => { setPayoutAmount(e.target.value); setPayoutError(null) }}
                            className="flex-1 h-9 text-sm border-gray-200"
                          />
                          <Button
                            type="submit"
                            disabled={payoutLoading}
                            size="sm"
                            className="bg-gray-900 hover:bg-gray-800 text-white gap-1.5 h-9"
                          >
                            {payoutLoading
                              ? <RefreshCw className="w-3.5 h-3.5 animate-spin" />
                              : <Send className="w-3.5 h-3.5" />
                            }
                            Valider
                          </Button>
                        </div>
                        <p className="text-[11px] text-gray-400">
                          Ce montant s'ajoute aux versements déjà effectués pour ajuster le solde.
                        </p>
                      </form>

                      <div className="pt-3 border-t border-gray-100">
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => setDeleteOpen(true)}
                          disabled={deleteLoading}
                          className="w-full text-rose-600 border-rose-200 hover:bg-rose-50 hover:text-rose-700 gap-1.5"
                        >
                          <Trash2 className="w-3.5 h-3.5" />
                          Supprimer cet influenceur
                        </Button>
                      </div>
                    </CardContent>
                  </Card>
                </div>
              )}

              {/* Dernières utilisations */}
              <Card className="border border-gray-200 shadow-none">
                <CardHeader className="px-5 py-4 border-b border-gray-100">
                  <CardTitle className="text-sm font-semibold text-gray-800 flex items-center gap-2">
                    <Activity className="w-4 h-4 text-rose-500" />
                    Dernières utilisations
                  </CardTitle>
                </CardHeader>
                <CardContent className="p-0">
                  {loading ? (
                    <div className="p-5 space-y-2">
                      {Array.from({ length: 3 }).map((_, i) => <Skeleton key={i} className="h-14 w-full rounded-lg" />)}
                    </div>
                  ) : !details || details.recentUsages.length === 0 ? (
                    <div className="py-10 text-center text-gray-400">
                      <Users className="w-7 h-7 mx-auto mb-2 opacity-30" />
                      <p className="text-sm">Aucune utilisation récente</p>
                    </div>
                  ) : (
                    <div className="divide-y divide-gray-100">
                      {details.recentUsages.map(usage => (
                        <div key={usage.id} className="flex items-center justify-between px-5 py-3 hover:bg-gray-50 transition-colors">
                          <div>
                            <p className="text-sm font-medium text-gray-900">
                              {usage.referredUser
                                ? `${usage.referredUser.firstName} ${usage.referredUser.lastName}`
                                : 'Utilisateur'}
                            </p>
                            {usage.referredUser?.phone && (
                              <p className="text-[11px] text-gray-400 flex items-center gap-1 mt-0.5">
                                <Phone className="w-3 h-3" /> {usage.referredUser.phone}
                              </p>
                            )}
                          </div>
                          <div className="text-right">
                            <p className="text-sm font-semibold text-gray-900 tabular-nums">{formatCurrency(usage.creditedAmount)}</p>
                            <p className="text-[11px] text-gray-400 flex items-center justify-end gap-1 mt-0.5">
                              <Calendar className="w-3 h-3" /> {formatDateDistance(usage.registeredAt)}
                            </p>
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                </CardContent>
              </Card>
            </TabsContent>

            {/* ── History ── */}
            <TabsContent value="history" className="mt-5 space-y-4">
              <div className="flex items-center gap-2">
                <div className="relative flex-1">
                  <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400 pointer-events-none" />
                  <Input
                    placeholder="Rechercher par nom ou téléphone…"
                    value={historySearch}
                    onChange={e => setHistorySearch(e.target.value)}
                    className="pl-8 h-8 text-xs border-gray-200"
                  />
                </div>
                <button
                  onClick={() => influencerId && fetchHistory(influencerId)}
                  disabled={historyLoading}
                  className="p-1.5 rounded-md hover:bg-gray-100 text-gray-400 hover:text-gray-600 transition-colors"
                >
                  <RefreshCw className={cn('w-3.5 h-3.5', historyLoading && 'animate-spin')} />
                </button>
              </div>

              <Card className="border border-gray-200 shadow-none overflow-hidden">
                <CardContent className="p-0">
                  <div className="overflow-x-auto">
                    <Table>
                      <TableHeader>
                        <TableRow className="bg-gray-50 hover:bg-gray-50 border-b border-gray-100">
                          <TableHead className="pl-5 text-[11px] font-semibold uppercase tracking-wider text-gray-400">Passager</TableHead>
                          <TableHead className="text-[11px] font-semibold uppercase tracking-wider text-gray-400">Téléphone</TableHead>
                          <TableHead className="text-[11px] font-semibold uppercase tracking-wider text-gray-400">Montant</TableHead>
                          <TableHead className="text-[11px] font-semibold uppercase tracking-wider text-gray-400">Canal</TableHead>
                          <TableHead className="pr-5 text-[11px] font-semibold uppercase tracking-wider text-gray-400">Date</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {historyLoading ? (
                          Array.from({ length: 4 }).map((_, i) => (
                            <TableRow key={i} className="border-b border-gray-100">
                              <TableCell className="pl-5"><Skeleton className="h-3.5 w-32" /></TableCell>
                              <TableCell><Skeleton className="h-3.5 w-24" /></TableCell>
                              <TableCell><Skeleton className="h-3.5 w-16" /></TableCell>
                              <TableCell><Skeleton className="h-5 w-14 rounded-md" /></TableCell>
                              <TableCell className="pr-5"><Skeleton className="h-3.5 w-20" /></TableCell>
                            </TableRow>
                          ))
                        ) : !history || history.data.length === 0 ? (
                          <TableRow>
                            <TableCell colSpan={5} className="py-10 text-center text-gray-400">
                              <Search className="w-7 h-7 mx-auto mb-2 opacity-30" />
                              <p className="text-sm">
                                {historyQuery ? `Aucun résultat pour "${historyQuery}"` : 'Aucune inscription enregistrée'}
                              </p>
                            </TableCell>
                          </TableRow>
                        ) : history.data.map(row => (
                          <TableRow key={row.id} className="border-b border-gray-100 hover:bg-gray-50 transition-colors">
                            <TableCell className="pl-5 text-sm font-medium text-gray-900">
                              {row.referredUser ? `${row.referredUser.firstName} ${row.referredUser.lastName}` : '—'}
                            </TableCell>
                            <TableCell className="text-sm text-gray-500">{row.referredUser?.phone || '—'}</TableCell>
                            <TableCell className="text-sm font-semibold text-gray-900 tabular-nums">{formatCurrency(row.creditedAmount)}</TableCell>
                            <TableCell>
                              <Badge variant="outline" className="text-[10px] bg-gray-50 text-gray-600 border-gray-200">
                                {row.registeredVia || 'Online'}
                              </Badge>
                            </TableCell>
                            <TableCell className="pr-5 text-xs text-gray-400">
                              {new Date(row.registeredAt).toLocaleDateString('fr-FR', { day: '2-digit', month: 'short', year: 'numeric' })}
                            </TableCell>
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                  </div>

                  {history && history.data.length > 0 && (
                    <div className="flex items-center justify-between px-5 py-3 border-t border-gray-100">
                      <p className="text-xs text-gray-400">
                        {(historyPage - 1) * history.meta.perPage + 1}–{Math.min(historyPage * history.meta.perPage, history.meta.total)} sur {history.meta.total}
                      </p>
                      <div className="flex items-center gap-1.5">
                        <Button variant="outline" size="sm" disabled={historyPage === 1} onClick={() => setHistoryPage(p => p - 1)} className="h-7 px-2.5 text-xs border-gray-200 gap-1">
                          Précédent
                        </Button>
                        <Button variant="outline" size="sm" disabled={historyPage >= history.meta.lastPage} onClick={() => setHistoryPage(p => p + 1)} className="h-7 px-2.5 text-xs border-gray-200 gap-1">
                          Suivant
                        </Button>
                      </div>
                    </div>
                  )}
                </CardContent>
              </Card>
            </TabsContent>
          </Tabs>
        </DialogContent>
      </Dialog>

      <ConfirmDialog
        title="Supprimer cet influenceur ?"
        description="Cette action est irréversible. L'influenceur et toutes ses données seront définitivement supprimés."
        open={deleteOpen}
        onOpenChange={setDeleteOpen}
        onConfirm={handleDelete}
      />
    </>
  )
}
