"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import { EyeIcon, Loader2Icon, MoreHorizontalIcon, PencilIcon, Trash2Icon } from "lucide-react"
import { toast } from "sonner"

import { Button } from "@/src/components/ui/button"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/src/components/ui/dropdown-menu"
import { useToggleItemAvailabilityMutation } from "@/src/state/menu"
import type { MenuItem } from "@/src/state/menu"
import { extractErrorMessage } from "../utils"

type Props = {
  item: MenuItem
  onPreview: (item: MenuItem) => void
  onDelete: (item: MenuItem) => void
}

export function ItemCard({ item, onPreview, onDelete }: Props) {
  const router = useRouter()
  const [toggleAvailability, { isLoading }] = useToggleItemAvailabilityMutation()
  const [toggling, setToggling] = useState(false)

  const handleToggle = async () => {
    setToggling(true)
    try {
      await toggleAvailability(item.id).unwrap()
    } catch (err) {
      toast.error(extractErrorMessage(err, "Erreur lors de la mise à jour"))
    } finally {
      setToggling(false)
    }
  }

  return (
    <div className="flex gap-3 rounded-xl border bg-white p-3 transition-shadow hover:shadow-sm">
      <div className="aspect-4/3 w-24 shrink-0 overflow-hidden rounded-lg bg-muted">
        {item.thumbnailImage ? (
          // eslint-disable-next-line @next/next/no-img-element
          <img
            src={item.thumbnailImage}
            alt={item.name}
            className="h-full w-full object-cover"
          />
        ) : (
          <div className="h-full w-full bg-muted" />
        )}
      </div>

      <div className="flex flex-1 flex-col gap-1 min-w-0">
        <div className="flex items-start justify-between gap-2">
          <div className="min-w-0">
            <p className="text-sm font-medium truncate">{item.name}</p>
            <p className="text-xs text-muted-foreground">{item.category.name}</p>
          </div>
          <p className="text-sm font-semibold shrink-0">
            {item.price.toLocaleString("fr-FR")} FCFA
          </p>
        </div>

        {item.description && (
          <p className="text-xs text-muted-foreground line-clamp-2">{item.description}</p>
        )}

        <div className="flex items-center justify-between mt-auto pt-1">
          <button
            type="button"
            disabled={toggling || isLoading}
            onClick={handleToggle}
            className={`inline-flex items-center gap-1.5 text-xs font-medium rounded-full px-2.5 py-1 transition-colors ${
              item.isAvailable
                ? "bg-emerald-50 text-emerald-700 hover:bg-emerald-100"
                : "bg-muted text-muted-foreground hover:bg-muted/80"
            }`}
          >
            {toggling ? (
              <Loader2Icon className="size-3 animate-spin" />
            ) : (
              <span
                className={`size-1.5 rounded-full ${item.isAvailable ? "bg-emerald-500" : "bg-muted-foreground"}`}
              />
            )}
            {item.isAvailable ? "Disponible" : "Indisponible"}
          </button>

          <DropdownMenu modal={false}>
            <DropdownMenuTrigger asChild>
              <Button variant="ghost" size="icon" className="size-7">
                <MoreHorizontalIcon className="size-3.5" />
                <span className="sr-only">Actions</span>
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end" className="w-44">
              <DropdownMenuItem onClick={() => onPreview(item)}>
                <div className="rounded-full bg-muted p-1.5">
                  <EyeIcon className="size-3.5" />
                </div>
                Aperçu
              </DropdownMenuItem>
              <DropdownMenuItem onClick={() => router.push(`/menu/items/${item.id}`)}>
                <div className="rounded-full bg-muted p-1.5">
                  <PencilIcon className="size-3.5" />
                </div>
                Modifier
              </DropdownMenuItem>
              <DropdownMenuItem
                className="text-destructive focus:text-destructive"
                onClick={() => onDelete(item)}
              >
                <div className="rounded-full bg-muted p-1.5">
                  <Trash2Icon className="size-3.5" />
                </div>
                Supprimer
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        </div>
      </div>
    </div>
  )
}
