'use client'

import { useState, useMemo, useEffect } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Skeleton } from '@/components/ui/skeleton'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import {
  Dialog, DialogContent, DialogHeader, DialogTitle,
  DialogDescription, DialogFooter,
} from '@/components/ui/dialog'
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import * as z from 'zod'
import {
  Plus, Pencil, Trash2, Wrench, RefreshCw,
  Search, X, ArrowLeft, ArrowRight, AlertCircle,
} from 'lucide-react'
import { useOperations } from '@/contexts/OperationsContext'
import { ConfirmDialog } from '@/components/ui/confirm-dialog'
import { cn } from '@/lib/utils'

// ── Types & schema ─────────────────────────────────────────────────────────────

interface Operation {
  id: number
  nom: string
  description: string
  statut: boolean | number
}

const schema = z.object({
  nom:         z.string().min(1, 'Nom requis').max(50, '50 caractères max'),
  description: z.string().min(1, 'Description requise').max(200, '200 caractères max'),
  statut:      z.boolean(),
})
type FormValues = z.infer<typeof schema>

const STATUS_FILTERS = [
  { value: 'all',      label: 'Toutes'    },
  { value: 'active',   label: 'Actives'   },
  { value: 'inactive', label: 'Inactives' },
] as const
type StatusFilter = typeof STATUS_FILTERS[number]['value']

// ── Form dialog ────────────────────────────────────────────────────────────────

function OperationDialog({
  open,
  operation,
  onSubmit,
  onClose,
}: {
  open: boolean
  operation: Operation | null
  onSubmit: (values: FormValues) => Promise<boolean>
  onClose: () => void
}) {
  const [submitError, setSubmitError] = useState<string | null>(null)

  const form = useForm<FormValues>({
    resolver: zodResolver(schema),
    defaultValues: { nom: '', description: '', statut: true },
  })

  useEffect(() => {
    if (open) {
      setSubmitError(null)
      form.reset({
        nom:         operation?.nom         ?? '',
        description: operation?.description ?? '',
        statut:      operation ? !!operation.statut : true,
      })
    }
  }, [open, operation])

  const handleOpenChange = (v: boolean) => {
    if (!v) { form.reset(); setSubmitError(null); onClose() }
  }

  const handleSubmit = async (values: FormValues) => {
    setSubmitError(null)
    try {
      const ok = await onSubmit(values)
      if (ok) { form.reset(); onClose() }
    } catch (err: unknown) {
      setSubmitError(err instanceof Error ? err.message : 'Une erreur est survenue')
    }
  }

  const isEditing = Boolean(operation)
  const isActive  = form.watch('statut')

  return (
    <Dialog open={open} onOpenChange={handleOpenChange}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>{isEditing ? "Modifier l'opération" : 'Nouvelle opération'}</DialogTitle>
          <DialogDescription>
            {isEditing ? 'Modifiez les informations ci-dessous.' : 'Remplissez les champs pour créer une opération.'}
          </DialogDescription>
        </DialogHeader>

        <Form {...form}>
          <form onSubmit={form.handleSubmit(handleSubmit)} className="space-y-4 pt-1">
            <FormField
              control={form.control}
              name="nom"
              render={({ field }) => (
                <FormItem>
                  <FormLabel className="text-xs font-semibold text-gray-600">Nom</FormLabel>
                  <FormControl>
                    <Input placeholder="Ex : create, read, update…" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="description"
              render={({ field }) => (
                <FormItem>
                  <FormLabel className="text-xs font-semibold text-gray-600">Description</FormLabel>
                  <FormControl>
                    <textarea
                      rows={3}
                      placeholder="Description détaillée de l'opération…"
                      {...field}
                      className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 resize-none"
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="statut"
              render={({ field }) => (
                <FormItem>
                  <button
                    type="button"
                    onClick={() => field.onChange(!field.value)}
                    className={cn(
                      'w-full flex items-center justify-between px-4 py-3 rounded-lg border text-sm font-medium transition-all',
                      isActive
                        ? 'bg-emerald-50 border-emerald-200 text-emerald-700'
                        : 'bg-gray-50 border-gray-200 text-gray-500'
                    )}
                  >
                    <span>Opération {isActive ? 'active' : 'inactive'}</span>
                    <div className={cn(
                      'w-9 h-5 rounded-full relative transition-colors duration-200',
                      isActive ? 'bg-emerald-500' : 'bg-gray-300'
                    )}>
                      <div className={cn(
                        'absolute top-0.5 w-4 h-4 bg-white rounded-full shadow transition-transform duration-200',
                        isActive ? 'translate-x-4' : 'translate-x-0.5'
                      )} />
                    </div>
                  </button>
                </FormItem>
              )}
            />

            {submitError && (
              <div className="flex items-center gap-2 rounded-lg bg-red-50 border border-red-200 px-3 py-2.5 text-sm text-red-700">
                <AlertCircle className="w-4 h-4 flex-shrink-0" />
                {submitError}
              </div>
            )}

            <DialogFooter className="pt-2">
              <Button type="button" variant="outline" onClick={onClose} className="text-xs">Annuler</Button>
              <Button type="submit" className="text-xs bg-red-600 hover:bg-red-700 text-white">
                {isEditing ? 'Enregistrer' : 'Créer'}
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  )
}

// ── Page ───────────────────────────────────────────────────────────────────────

export default function OperationsPage() {
  const { operations, loading, fetchOperations, createOperation, updateOperation, deleteOperation } = useOperations()

  const [search, setSearch]             = useState('')
  const [statusFilter, setStatusFilter] = useState<StatusFilter>('all')
  const [dialogOpen, setDialogOpen]     = useState(false)
  const [editing, setEditing]           = useState<Operation | null>(null)
  const [deleteTarget, setDeleteTarget] = useState<Operation | null>(null)
  const [page, setPage]                 = useState(1)
  const PER_PAGE = 10

  const filtered = useMemo(() => operations.filter((o) => {
    const matchSearch =
      o.nom.toLowerCase().includes(search.toLowerCase()) ||
      o.description.toLowerCase().includes(search.toLowerCase())
    if (statusFilter === 'active')   return matchSearch && !!o.statut
    if (statusFilter === 'inactive') return matchSearch && !o.statut
    return matchSearch
  }), [operations, search, statusFilter])

  const lastPage  = Math.max(1, Math.ceil(filtered.length / PER_PAGE))
  const paginated = filtered.slice((page - 1) * PER_PAGE, page * PER_PAGE)
  const from      = filtered.length === 0 ? 0 : (page - 1) * PER_PAGE + 1
  const to        = Math.min(page * PER_PAGE, filtered.length)

  useEffect(() => { setPage(1) }, [search, statusFilter])

  const activeCount   = operations.filter(o => !!o.statut).length
  const inactiveCount = operations.length - activeCount

  const openCreate  = () => { setEditing(null); setDialogOpen(true) }
  const openEdit    = (o: Operation) => { setEditing(o); setDialogOpen(true) }
  const closeDialog = () => { setDialogOpen(false); setEditing(null) }

  const handleSubmit = async (values: FormValues) => {
    if (editing) return updateOperation(editing.id, values)
    return createOperation(values)
  }

  const handleDelete = async () => {
    if (!deleteTarget) return
    await deleteOperation(deleteTarget.id)
    setDeleteTarget(null)
  }

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

        {/* Header */}
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-xl font-semibold text-gray-900">Opérations</h1>
            <p className="text-sm text-gray-400 mt-0.5">Actions disponibles dans le système de permissions</p>
          </div>
          <Button
            size="sm"
            onClick={openCreate}
            className="gap-2 text-xs bg-red-600 hover:bg-red-700 text-white"
          >
            <Plus className="w-3.5 h-3.5" />
            Nouvelle opération
          </Button>
        </div>

        {/* KPI row */}
        <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
          {[
            { label: 'Total',     value: operations.length, color: 'text-gray-600',    bg: 'bg-gray-100'   },
            { label: 'Actives',   value: activeCount,       color: 'text-emerald-600', bg: 'bg-emerald-50' },
            { label: 'Inactives', value: inactiveCount,     color: 'text-gray-400',    bg: 'bg-gray-100'   },
          ].map(({ label, value, color, bg }) => (
            <Card key={label} className="border border-gray-200 shadow-none bg-white">
              <CardContent className="p-5">
                <div className={cn('w-8 h-8 rounded-lg flex items-center justify-center mb-3', bg)}>
                  <Wrench className={cn('w-4 h-4', color)} />
                </div>
                {loading
                  ? <Skeleton className="h-7 w-12 mb-1" />
                  : <p className="text-2xl font-bold text-gray-900 tabular-nums">{value}</p>
                }
                <p className="text-xs font-medium text-gray-400 mt-1">{label}</p>
              </CardContent>
            </Card>
          ))}
        </div>

        {/* Main table card */}
        <Card className="border border-gray-200 shadow-none bg-white overflow-hidden">
          <CardHeader className="px-6 py-4 border-b border-gray-100">
            <div className="flex flex-col gap-3">
              <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">
                  <Wrench className="w-4 h-4 text-rose-500" />
                  {loading ? 'Opérations' : `${filtered.length} opération${filtered.length > 1 ? 's' : ''}`}
                </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={search}
                      onChange={e => setSearch(e.target.value)}
                      className="pl-8 h-8 text-xs border-gray-200 w-48"
                    />
                    {search && (
                      <button onClick={() => setSearch('')} 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>
                  <button
                    onClick={fetchOperations}
                    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={cn('w-3.5 h-3.5', loading && 'animate-spin')} />
                  </button>
                </div>
              </div>

              {/* Status pills */}
              <div className="flex items-center gap-1.5">
                {STATUS_FILTERS.map(({ value, label }) => (
                  <button
                    key={value}
                    onClick={() => setStatusFilter(value)}
                    className={cn(
                      'px-2.5 py-1 rounded-md text-[11px] font-medium border transition-all',
                      statusFilter === value
                        ? 'bg-gray-900 text-white border-gray-900'
                        : 'bg-white text-gray-500 border-gray-200 hover:border-gray-300 hover:text-gray-700'
                    )}
                  >
                    {label}
                  </button>
                ))}
              </div>
            </div>
          </CardHeader>

          <CardContent className="p-0">
            <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">Opération</TableHead>
                  <TableHead className="text-[11px] font-semibold uppercase tracking-wider text-gray-400">Description</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 ? (
                  Array.from({ length: 6 }).map((_, i) => (
                    <TableRow key={i} className="border-b border-gray-100">
                      <TableCell className="pl-6"><Skeleton className="h-3.5 w-36" /></TableCell>
                      <TableCell><Skeleton className="h-3.5 w-56" /></TableCell>
                      <TableCell><Skeleton className="h-5 w-16 rounded-full" /></TableCell>
                      <TableCell className="pr-6 text-right">
                        <div className="flex items-center justify-end gap-1">
                          <Skeleton className="h-7 w-7 rounded-md" />
                          <Skeleton className="h-7 w-7 rounded-md" />
                        </div>
                      </TableCell>
                    </TableRow>
                  ))
                ) : filtered.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={4} className="py-14 text-center">
                      <Wrench className="w-7 h-7 mx-auto mb-2 text-gray-300" />
                      <p className="text-sm text-gray-400">
                        {search ? `Aucun résultat pour "${search}"` : 'Aucune opération'}
                      </p>
                    </TableCell>
                  </TableRow>
                ) : paginated.map(o => {
                  const isActive = !!o.statut
                  return (
                    <TableRow key={o.id} className="border-b border-gray-100 hover:bg-gray-50 transition-colors">
                      <TableCell className="pl-6">
                        <div className="flex items-center gap-2.5">
                          <div className={cn(
                            'w-7 h-7 rounded-lg flex items-center justify-center flex-shrink-0',
                            isActive ? 'bg-emerald-50' : 'bg-gray-100'
                          )}>
                            <Wrench className={cn('w-3.5 h-3.5', isActive ? 'text-emerald-600' : 'text-gray-400')} />
                          </div>
                          <span className="text-sm font-semibold text-gray-900">{o.nom}</span>
                        </div>
                      </TableCell>
                      <TableCell className="text-xs text-gray-500 max-w-[260px]">
                        <span className="line-clamp-2">{o.description}</span>
                      </TableCell>
                      <TableCell>
                        <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 ? 'Active' : 'Inactive'}
                        </span>
                      </TableCell>
                      <TableCell className="pr-6">
                        <div className="flex items-center justify-end gap-1">
                          <button
                            onClick={() => openEdit(o)}
                            className="p-1.5 rounded-md hover:bg-blue-50 text-gray-400 hover:text-blue-600 transition-colors"
                            title="Modifier"
                          >
                            <Pencil className="w-3.5 h-3.5" />
                          </button>
                          <button
                            onClick={() => setDeleteTarget(o)}
                            className="p-1.5 rounded-md hover:bg-red-50 text-gray-400 hover:text-red-600 transition-colors"
                            title="Supprimer"
                          >
                            <Trash2 className="w-3.5 h-3.5" />
                          </button>
                        </div>
                      </TableCell>
                    </TableRow>
                  )
                })}
              </TableBody>
            </Table>

            {/* Pagination footer */}
            {!loading && filtered.length > PER_PAGE && (
              <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 {filtered.length}
                </p>
                <div className="flex items-center gap-1.5">
                  <Button
                    variant="outline"
                    size="sm"
                    disabled={page === 1}
                    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>
                  <span className="text-xs text-gray-400 tabular-nums px-1">
                    {page} / {lastPage}
                  </span>
                  <Button
                    variant="outline"
                    size="sm"
                    disabled={page >= lastPage}
                    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>
      </div>

      {/* Create / Edit dialog */}
      <OperationDialog
        open={dialogOpen}
        operation={editing}
        onSubmit={handleSubmit}
        onClose={closeDialog}
      />

      {/* Delete confirmation */}
      <ConfirmDialog
        open={Boolean(deleteTarget)}
        onOpenChange={open => { if (!open) setDeleteTarget(null) }}
        title="Supprimer l'opération ?"
        description={`"${deleteTarget?.nom}" sera définitivement supprimée. Cette action est irréversible.`}
        onConfirm={handleDelete}
      />
    </>
  )
}
