'use client';

import { useState, useEffect, useCallback } from 'react';
import { Menu as MenuIcon, Plus, Trash2, Pencil, Eye, EyeOff } from 'lucide-react';
import { Card, CardContent } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { Switch } from '@/components/ui/switch';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from '@/components/ui/alert-dialog';

const ORANGE_BTN = 'bg-gradient-to-r from-orange-600 to-amber-500 shadow-sm';

export function AdminMenus() {
  const [menus, setMenus] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [showDialog, setShowDialog] = useState(false);
  const [editMenu, setEditMenu] = useState<any>(null);
  const [form, setForm] = useState({ title: '', slug: '', icon: '', path: '', order: 0, parentId: '', isVisible: true });
  const [formLoading, setFormLoading] = useState(false);

  const fetchMenus = useCallback(async () => {
    try { const r = await fetch('/api/admin/menus'); const d = await r.json(); if (d.success) setMenus(d.menus || []); } catch { }
    finally { setLoading(false); }
  }, []);
  useEffect(() => { fetchMenus(); }, [fetchMenus]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault(); setFormLoading(true);
    try {
      const method = editMenu ? 'PATCH' : 'POST';
      const body = editMenu ? { id: editMenu.id, ...form, parentId: form.parentId || null } : { ...form, parentId: form.parentId || null };
      await fetch('/api/admin/menus', { method, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
    } catch { }
    setShowDialog(false); setEditMenu(null); setForm({ title: '', slug: '', icon: '', path: '', order: 0, parentId: '', isVisible: true }); fetchMenus(); setFormLoading(false);
  };

  const handleDelete = async (id: string) => {
    try { await fetch('/api/admin/menus', { method: 'DELETE', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id }) }); } catch { }
    fetchMenus();
  };

  const toggleVisible = async (menu: any) => {
    try { await fetch('/api/admin/menus', { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id: menu.id, isVisible: !menu.isVisible }) }); } catch { }
    fetchMenus();
  };

  const openEdit = (menu: any) => { setEditMenu(menu); setForm({ title: menu.title, slug: menu.slug, icon: menu.icon || '', path: menu.path || '', order: menu.order || 0, parentId: menu.parentId || '', isVisible: menu.isVisible ?? true }); setShowDialog(true); };

  if (loading) return <div className="flex items-center justify-center py-20"><span className="h-8 w-8 animate-spin rounded-full border-4 border-orange-500 border-t-transparent" /></div>;

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <p className="text-sm text-muted-foreground">{menus.length} menu items</p>
        <Button className={`gap-2 ${ORANGE_BTN}`} onClick={() => { setEditMenu(null); setForm({ title: '', slug: '', icon: '', path: '', order: 0, parentId: '', isVisible: true }); setShowDialog(true); }}><Plus className="h-4 w-4" />Add Menu</Button>
      </div>
      <div className="space-y-2">
        {menus.map((menu) => (
          <Card key={menu.id} className="border-0 shadow-sm">
            <CardContent className="flex items-center justify-between p-4">
              <div className="flex items-center gap-3">
                <MenuIcon className="h-4 w-4 text-orange-500" />
                <div>
                  <div className="flex items-center gap-2"><p className="text-sm font-medium">{menu.title}</p><Badge variant="outline" className="text-[10px]">{menu.slug}</Badge>{!menu.isVisible && <Badge className="bg-slate-100 text-slate-500 text-[10px] border-0">Hidden</Badge>}</div>
                  <p className="text-xs text-muted-foreground">{menu.path || '/'}</p>
                </div>
              </div>
              <div className="flex items-center gap-2">
                <Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => toggleVisible(menu)}>{menu.isVisible ? <Eye className="h-3.5 w-3.5" /> : <EyeOff className="h-3.5 w-3.5 text-muted-foreground" />}</Button>
                <Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => openEdit(menu)}><Pencil className="h-3.5 w-3.5" /></Button>
                <AlertDialog><AlertDialogTrigger asChild><Button variant="ghost" size="icon" className="h-8 w-8"><Trash2 className="h-3.5 w-3.5 text-destructive" /></Button></AlertDialogTrigger>
                  <AlertDialogContent><AlertDialogHeader><AlertDialogTitle>Delete Menu</AlertDialogTitle><AlertDialogDescription>Delete &quot;{menu.title}&quot;?</AlertDialogDescription></AlertDialogHeader><AlertDialogFooter><AlertDialogCancel>Cancel</AlertDialogCancel><AlertDialogAction onClick={() => handleDelete(menu.id)} className="bg-destructive text-destructive-foreground">Delete</AlertDialogAction></AlertDialogFooter></AlertDialogContent>
                </AlertDialog>
              </div>
            </CardContent>
          </Card>
        ))}
        {menus.length === 0 && <div className="py-16 text-center"><MenuIcon className="mx-auto h-12 w-12 text-slate-300" strokeWidth={1.5} /><p className="mt-3 text-sm text-muted-foreground">No menu items</p></div>}
      </div>

      <Dialog open={showDialog} onOpenChange={(o) => { setShowDialog(o); if (!o) setEditMenu(null); }}>
        <DialogContent className="sm:max-w-[420px]"><DialogHeader><DialogTitle>{editMenu ? 'Edit Menu' : 'Add Menu'}</DialogTitle><DialogDescription>{editMenu ? 'Update menu item' : 'Create a new navigation menu item'}</DialogDescription></DialogHeader>
          <form onSubmit={handleSubmit} className="space-y-3 pt-2">
            <div className="grid grid-cols-2 gap-3">
              <div className="space-y-1.5"><Label className="text-xs font-medium">Title</Label><Input value={form.title} onChange={(e) => setForm({ ...form, title: e.target.value })} required /></div>
              <div className="space-y-1.5"><Label className="text-xs font-medium">Slug</Label><Input value={form.slug} onChange={(e) => setForm({ ...form, slug: e.target.value })} required /></div>
            </div>
            <div className="grid grid-cols-2 gap-3">
              <div className="space-y-1.5"><Label className="text-xs font-medium">Icon</Label><Input value={form.icon} onChange={(e) => setForm({ ...form, icon: e.target.value })} placeholder="Home" /></div>
              <div className="space-y-1.5"><Label className="text-xs font-medium">Path</Label><Input value={form.path} onChange={(e) => setForm({ ...form, path: e.target.value })} placeholder="/" /></div>
            </div>
            <div className="grid grid-cols-2 gap-3">
              <div className="space-y-1.5"><Label className="text-xs font-medium">Order</Label><Input type="number" value={form.order} onChange={(e) => setForm({ ...form, order: parseInt(e.target.value) || 0 })} /></div>
              <div className="space-y-1.5 flex items-end"><div className="flex items-center gap-2"><Switch checked={form.isVisible} onCheckedChange={(v) => setForm({ ...form, isVisible: v })} /><Label className="text-xs">Visible</Label></div></div>
            </div>
            <Button type="submit" className={`w-full ${ORANGE_BTN} font-semibold`} disabled={formLoading}>{formLoading ? 'Saving...' : editMenu ? 'Update' : 'Create'}</Button>
          </form>
        </DialogContent>
      </Dialog>
    </div>
  );
}
