'use client'

import { useState, useEffect } from 'react'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import { Skeleton } from '@/components/ui/skeleton'
import {
  Table, TableBody, TableCell,
  TableHead, TableHeader, TableRow,
} from '@/components/ui/table'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import {
  Search, RefreshCw, Trash2,
  ArrowRightLeft, Power, Copy,
  ArrowLeft, ArrowRight, Building2, X,
} from 'lucide-react'
import { toast } from 'sonner'
import { useRoutes } from '@/contexts/RoutesContext'
import { getAllCities } from '@/lib/cities'
import { getCompanies } from '@/lib/companies'
import { toggleRouteActive, copyRouteToCompany } from '@/lib/routes_lib'
import { ConfirmDialog } from '@/components/ui/confirm-dialog'
import { RouteDialog } from '@/components/routes/routes-dialog'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog'

const PER_PAGE_OPTIONS = [10, 25, 50]

export default function RoutesPage() {
  const { routes, meta, loading, error, fetchRoutes, removeRoute } = useRoutes()

  const [cityMap, setCityMap] = useState<Record<number, string>>({})
  const [companyMap, setCompanyMap] = useState<Record<number, string>>({})
  const [companies, setCompanies] = useState<{ id: number; name: string }[]>([])

  const [q, setQ] = useState('')
  const [page, setPage] = useState(1)
  const [perPage, setPerPage] = useState(25)
  const [deleteId, setDeleteId] = useState<number | null>(null)
  const [copyId, setCopyId] = useState<number | null>(null)
  const [targetCompanyId, setTargetCompanyId] = useState<number | ''>('')
  const [copyLoading, setCopyLoading] = useState(false)

  useEffect(() => {
    getAllCities()
      .then(list => setCityMap(list.reduce<Record<number, string>>((a, c) => { a[c.id] = c.name; return a }, {})))
      .catch(() => {})
    getCompanies({ perPage: 1000 })
      .then(res => {
        setCompanies(res.data)
        setCompanyMap(res.data.reduce<Record<number, string>>((a, c) => { a[c.id] = c.name; return a }, {}))
      })
      .catch(() => {})
  }, [])

  useEffect(() => {
    fetchRoutes({ page, perPage, q })
  }, [fetchRoutes, page, perPage, q])

  const refresh = () => fetchRoutes({ page, perPage, q })

  const handleDelete = async () => {
    if (!deleteId) return
    try {
      await removeRoute(deleteId)
      toast.success('Route supprimée')
      if (routes.length === 1 && page > 1) setPage(p => p - 1)
    } catch {
      toast.error('Erreur lors de la suppression')
    } finally {
      setDeleteId(null)
    }
  }

  const handleToggle = async (id: number) => {
    try {
      const res = await toggleRouteActive(id)
      toast.success(res.message)
      refresh()
    } catch (err) {
      toast.error(err instanceof Error ? err.message : 'Impossible de modifier le statut.')
    }
  }

  const handleCopy = async () => {
    if (!copyId || !targetCompanyId) return
    setCopyLoading(true)
    try {
      const res = await copyRouteToCompany(copyId, Number(targetCompanyId))
      toast.success(res.message)
      refresh()
      setCopyId(null)
    } catch (err) {
      toast.error(err instanceof Error ? err.message : 'Impossible de copier cette route.')
    } finally {
      setCopyLoading(false)
    }
  }

  const cityName = (id: number, fallback?: string) => cityMap[id] ?? fallback ?? `#${id}`
  const companyName = (id: number, fallback?: string) => companyMap[id] ?? fallback ?? `#${id}`

  const from = (page - 1) * perPage + 1
  const to = Math.min(page * perPage, meta.total)

  return (
    <div className="space-y-5">

      {/* ── Header ── */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-xl font-semibold text-gray-900">Routes</h1>
          <p className="text-sm text-gray-400 mt-0.5">Trajets du réseau</p>
        </div>
        <RouteDialog onSuccess={refresh} />
      </div>

      {/* ── Main card ── */}
      <Card className="border border-gray-200 shadow-none bg-white overflow-hidden">

        {/* Toolbar */}
        <CardHeader className="px-6 py-4 border-b border-gray-100">
          <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
            <CardTitle className="text-sm font-semibold text-gray-800 flex items-center gap-2">
              <ArrowRightLeft className="w-4 h-4 text-rose-500" />
              {meta.total > 0 ? `${meta.total} route${meta.total > 1 ? 's' : ''}` : 'Routes'}
            </CardTitle>

            <div className="flex items-center gap-2">
              <div className="relative">
                <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…"
                  value={q}
                  onChange={e => { setQ(e.target.value); setPage(1) }}
                  className="pl-8 h-8 text-xs border-gray-200 w-44"
                />
                {q && (
                  <button
                    onClick={() => { setQ(''); setPage(1) }}
                    className="absolute right-2 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
                  >
                    <X className="w-3 h-3" />
                  </button>
                )}
              </div>

              <select
                value={perPage}
                onChange={e => { setPerPage(Number(e.target.value)); setPage(1) }}
                className="h-8 border border-gray-200 rounded-md px-2 text-xs text-gray-600 bg-white focus:outline-none focus:border-gray-300"
              >
                {PER_PAGE_OPTIONS.map(n => (
                  <option key={n} value={n}>{n} / page</option>
                ))}
              </select>

              <button
                onClick={refresh}
                disabled={loading}
                className="p-1.5 rounded-md hover:bg-gray-100 text-gray-400 hover:text-gray-600 transition-colors"
                title="Actualiser"
              >
                <RefreshCw className={`w-3.5 h-3.5 ${loading ? 'animate-spin' : ''}`} />
              </button>
            </div>
          </div>
        </CardHeader>

        <CardContent className="p-0">
          {error ? (
            <div className="flex items-center gap-2 m-6 text-sm text-rose-600 bg-rose-50 border border-rose-200 rounded-lg px-4 py-3">
              <X className="w-4 h-4 flex-shrink-0" />
              {error}
            </div>
          ) : (
            <>
              {/* Table — desktop */}
              <div className="hidden sm:block overflow-x-auto">
                <Table>
                  <TableHeader>
                    <TableRow className="bg-gray-50 hover:bg-gray-50 border-b border-gray-100">
                      <TableHead className="pl-6 text-[11px] font-semibold uppercase tracking-wider text-gray-400">Trajet</TableHead>
                      <TableHead className="text-[11px] font-semibold uppercase tracking-wider text-gray-400">Compagnie</TableHead>
                      <TableHead className="text-[11px] font-semibold uppercase tracking-wider text-gray-400">Prix</TableHead>
                      <TableHead className="text-[11px] font-semibold uppercase tracking-wider text-gray-400">Statut</TableHead>
                      <TableHead className="pr-6 text-right text-[11px] font-semibold uppercase tracking-wider text-gray-400">Actions</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {loading && routes.length === 0 ? (
                      Array.from({ length: 6 }).map((_, i) => (
                        <TableRow key={i} className="border-b border-gray-100">
                          <TableCell className="pl-6">
                            <div className="flex items-center gap-3">
                              <Skeleton className="w-8 h-8 rounded-lg flex-shrink-0" />
                              <div className="space-y-1.5">
                                <Skeleton className="h-3.5 w-40" />
                                <Skeleton className="h-3 w-10" />
                              </div>
                            </div>
                          </TableCell>
                          <TableCell><Skeleton className="h-5 w-24 rounded-md" /></TableCell>
                          <TableCell><Skeleton className="h-3.5 w-20" /></TableCell>
                          <TableCell><Skeleton className="h-5 w-16 rounded-full" /></TableCell>
                          <TableCell className="pr-6 text-right"><Skeleton className="h-7 w-20 ml-auto" /></TableCell>
                        </TableRow>
                      ))
                    ) : routes.length === 0 ? (
                      <TableRow>
                        <TableCell colSpan={5} className="py-14 text-center text-gray-400">
                          <ArrowRightLeft className="w-7 h-7 mx-auto mb-2 opacity-30" />
                          <p className="text-sm">
                            {q ? `Aucun résultat pour "${q}"` : 'Aucune route enregistrée'}
                          </p>
                        </TableCell>
                      </TableRow>
                    ) : routes.map(r => {
                      const isActive = Boolean(r.isActive)
                      return (
                        <TableRow key={r.id} className="border-b border-gray-100 hover:bg-gray-50 transition-colors">
                          <TableCell className="pl-6">
                            <div className="flex items-center gap-3">
                              <div className="w-8 h-8 rounded-lg bg-rose-50 flex items-center justify-center flex-shrink-0">
                                <ArrowRightLeft className="w-3.5 h-3.5 text-rose-500" />
                              </div>
                              <div className="min-w-0">
                                <p className="text-sm font-medium text-gray-900">
                                  {cityName(r.departureCityId, r.departureCity?.name)} → {cityName(r.arrivalCityId, r.arrivalCity?.name)}
                                </p>
                                <p className="text-[11px] text-gray-400">#{r.id}</p>
                              </div>
                            </div>
                          </TableCell>
                          <TableCell>
                            <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-md text-[11px] font-medium bg-gray-50 text-gray-600 border border-gray-200">
                              <Building2 className="w-3 h-3" />
                              {companyName(r.companyId, r.company?.name)}
                            </span>
                          </TableCell>
                          <TableCell>
                            <span className="text-sm font-medium text-gray-900">{r.basePrice.toLocaleString()} FCFA</span>
                          </TableCell>
                          <TableCell>
                            <button
                              onClick={() => handleToggle(r.id)}
                              className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[11px] font-medium transition-colors ${
                                isActive
                                  ? 'bg-emerald-50 text-emerald-700 ring-1 ring-inset ring-emerald-600/10 hover:bg-emerald-100'
                                  : 'bg-gray-100 text-gray-500 ring-1 ring-inset ring-gray-300/50 hover:bg-gray-200'
                              }`}
                            >
                              <Power className="h-3 w-3" />
                              {isActive ? 'Actif' : 'Inactif'}
                            </button>
                          </TableCell>
                          <TableCell className="pr-6">
                            <div className="flex justify-end gap-1">
                              <RouteDialog route={r} onSuccess={refresh} />
                              <button
                                onClick={() => { setCopyId(r.id); setTargetCompanyId('') }}
                                className="p-1.5 rounded-md hover:bg-blue-50 text-gray-400 hover:text-blue-600 transition-colors"
                                title="Copier"
                              >
                                <Copy className="w-3.5 h-3.5" />
                              </button>
                              <button
                                onClick={() => setDeleteId(r.id)}
                                className="p-1.5 rounded-md hover:bg-rose-50 text-gray-400 hover:text-rose-600 transition-colors"
                                title="Supprimer"
                              >
                                <Trash2 className="w-3.5 h-3.5" />
                              </button>
                            </div>
                          </TableCell>
                        </TableRow>
                      )
                    })}
                  </TableBody>
                </Table>
              </div>

              {/* List — mobile */}
              <div className="sm:hidden divide-y divide-gray-100">
                {loading && routes.length === 0 ? (
                  Array.from({ length: 4 }).map((_, i) => (
                    <div key={i} className="flex items-center gap-3 px-5 py-3.5">
                      <Skeleton className="w-9 h-9 rounded-lg flex-shrink-0" />
                      <div className="flex-1 space-y-1.5">
                        <Skeleton className="h-3.5 w-40" />
                        <Skeleton className="h-3 w-28" />
                      </div>
                    </div>
                  ))
                ) : routes.length === 0 ? (
                  <div className="py-12 text-center text-gray-400">
                    <ArrowRightLeft className="w-7 h-7 mx-auto mb-2 opacity-30" />
                    <p className="text-sm">{q ? `Aucun résultat pour "${q}"` : 'Aucune route'}</p>
                  </div>
                ) : routes.map(r => {
                  const isActive = Boolean(r.isActive)
                  return (
                    <div key={r.id} className="flex items-center justify-between px-5 py-3.5">
                      <div className="flex items-center gap-3 min-w-0">
                        <div className="w-9 h-9 rounded-lg bg-rose-50 flex items-center justify-center flex-shrink-0">
                          <ArrowRightLeft className="w-4 h-4 text-rose-500" />
                        </div>
                        <div className="min-w-0">
                          <p className="text-sm font-medium text-gray-900 truncate">
                            {cityName(r.departureCityId, r.departureCity?.name)} → {cityName(r.arrivalCityId, r.arrivalCity?.name)}
                          </p>
                          <p className="text-[11px] text-gray-400 truncate">
                            {companyName(r.companyId, r.company?.name)} · {r.basePrice.toLocaleString()} FCFA
                          </p>
                        </div>
                      </div>
                      <div className="flex items-center gap-1 ml-3 flex-shrink-0">
                        <button
                          onClick={() => handleToggle(r.id)}
                          className={`px-2 py-0.5 rounded-full text-[10px] font-medium ${
                            isActive ? 'bg-emerald-50 text-emerald-700' : 'bg-gray-100 text-gray-500'
                          }`}
                        >
                          {isActive ? 'Actif' : 'Inactif'}
                        </button>
                        <RouteDialog route={r} onSuccess={refresh} />
                        <button
                          onClick={() => { setCopyId(r.id); setTargetCompanyId('') }}
                          className="p-2 rounded-md hover:bg-blue-50 text-gray-400 hover:text-blue-600 transition-colors"
                        >
                          <Copy className="w-4 h-4" />
                        </button>
                        <button
                          onClick={() => setDeleteId(r.id)}
                          className="p-2 rounded-md hover:bg-rose-50 text-gray-400 hover:text-rose-600 transition-colors"
                        >
                          <Trash2 className="w-4 h-4" />
                        </button>
                      </div>
                    </div>
                  )
                })}
              </div>

              {/* Pagination */}
              {meta.total > 0 && (
                <div className="flex items-center justify-between px-6 py-3 border-t border-gray-100">
                  <p className="text-xs text-gray-400">{from}–{to} sur {meta.total}</p>
                  <div className="flex items-center gap-1.5">
                    <Button
                      variant="outline" size="sm"
                      disabled={page === 1 || loading}
                      onClick={() => setPage(p => p - 1)}
                      className="h-7 px-2.5 text-xs border-gray-200 gap-1"
                    >
                      <ArrowLeft className="w-3 h-3" />
                      Précédent
                    </Button>
                    <Button
                      variant="outline" size="sm"
                      disabled={page === meta.lastPage || loading}
                      onClick={() => setPage(p => p + 1)}
                      className="h-7 px-2.5 text-xs border-gray-200 gap-1"
                    >
                      Suivant
                      <ArrowRight className="w-3 h-3" />
                    </Button>
                  </div>
                </div>
              )}
            </>
          )}
        </CardContent>
      </Card>

      <ConfirmDialog
        title="Supprimer la route ?"
        description="Cette action est irréversible. La route sera définitivement supprimée du système."
        open={!!deleteId}
        onOpenChange={open => { if (!open) setDeleteId(null) }}
        onConfirm={handleDelete}
      />

      <Dialog open={!!copyId} onOpenChange={open => { if (!open) setCopyId(null) }}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle className="text-base font-semibold">Copier la route</DialogTitle>
          </DialogHeader>
          <div className="py-3">
            <label className="text-xs font-semibold uppercase tracking-wider text-gray-400 mb-2 block">
              Compagnie cible
            </label>
            <select
              value={targetCompanyId}
              onChange={e => setTargetCompanyId(Number(e.target.value) || '')}
              className="w-full border border-gray-200 rounded-md px-3 py-2 text-sm focus:outline-none focus:border-gray-300 bg-white"
            >
              <option value="">Sélectionner une compagnie…</option>
              {companies.map(c => (
                <option key={c.id} value={c.id}>{c.name}</option>
              ))}
            </select>
          </div>
          <DialogFooter>
            <Button variant="outline" size="sm" onClick={() => setCopyId(null)} className="text-xs">
              Annuler
            </Button>
            <Button
              size="sm"
              disabled={!targetCompanyId || copyLoading}
              onClick={handleCopy}
              className="bg-red-600 hover:bg-red-700 text-white text-xs gap-2"
            >
              {copyLoading
                ? <RefreshCw className="h-3.5 w-3.5 animate-spin" />
                : <Copy className="h-3.5 w-3.5" />}
              Copier
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

    </div>
  )
}
