'use client';

import { useState, useEffect, useCallback } from 'react';
import { Crown, Shield, Users, Plus, Trash2, Pencil, Key, CheckCircle, XCircle } 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 { 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';

interface Role {
  id: string; name: string; displayName: string; description: string;
  permissions: string[]; isSystem: boolean; color: string; userCount: number;
}

const AVAILABLE_PERMISSIONS = [
  { key: 'dashboard', label: 'Dashboard', group: 'General' },
  { key: 'users.view', label: 'View Users', group: 'Users' },
  { key: 'users.create', label: 'Create Users', group: 'Users' },
  { key: 'users.edit', label: 'Edit Users', group: 'Users' },
  { key: 'users.delete', label: 'Delete Users', group: 'Users' },
  { key: 'listings.view', label: 'View Listings', group: 'Listings' },
  { key: 'listings.create', label: 'Create Listings', group: 'Listings' },
  { key: 'listings.edit', label: 'Edit Listings', group: 'Listings' },
  { key: 'listings.delete', label: 'Delete Listings', group: 'Listings' },
  { key: 'orders.view', label: 'View Orders', group: 'Orders' },
  { key: 'orders.manage', label: 'Manage Orders', group: 'Orders' },
  { key: 'mcq.view', label: 'View MCQ', group: 'Education' },
  { key: 'mcq.manage', label: 'Manage MCQ', group: 'Education' },
  { key: 'menus.manage', label: 'Manage Menus', group: 'Settings' },
  { key: 'teams.view', label: 'View Teams', group: 'Teams' },
  { key: 'teams.manage', label: 'Manage Teams', group: 'Teams' },
  { key: 'settings.view', label: 'View Settings', group: 'Settings' },
  { key: 'settings.edit', label: 'Edit Settings', group: 'Settings' },
  { key: 'community.moderate', label: 'Moderate Community', group: 'Community' },
  { key: 'notifications.send', label: 'Send Notifications', group: 'Notifications' },
  { key: 'roles.manage', label: 'Manage Roles', group: 'Admin' },
];

const ROLE_COLORS = [
  'bg-orange-500', 'bg-orange-600', 'bg-emerald-500', 'bg-amber-500',
  'bg-rose-500', 'bg-amber-500', 'bg-yellow-500', 'bg-amber-600',
];

export function AdminRoles() {
  const [roles, setRoles] = useState<Role[]>([]);
  const [loading, setLoading] = useState(true);
  const [showDialog, setShowDialog] = useState(false);
  const [editRole, setEditRole] = useState<Role | null>(null);
  const [form, setForm] = useState({ name: '', displayName: '', description: '', permissions: [] as string[], color: 'bg-orange-500' });
  const [formLoading, setFormLoading] = useState(false);

  const fetchRoles = useCallback(async () => {
    try {
      const r = await fetch('/api/admin/roles');
      const d = await r.json();
      if (d.success) {
        setRoles(d.roles?.length ? d.roles : getDefaultRoles());
      } else {
        setRoles(getDefaultRoles());
      }
    } catch { setRoles(getDefaultRoles()); }
    finally { setLoading(false); }
  }, []);

  useEffect(() => { fetchRoles(); }, [fetchRoles]);

  const getDefaultRoles = (): Role[] => [
    { id: '1', name: 'super_admin', displayName: 'Super Admin', description: 'Full access to everything', permissions: AVAILABLE_PERMISSIONS.map(p => p.key), isSystem: true, color: 'bg-orange-500', userCount: 1 },
    { id: '2', name: 'admin', displayName: 'Admin', description: 'Manage most things except roles', permissions: AVAILABLE_PERMISSIONS.filter(p => p.group !== 'Admin').map(p => p.key), isSystem: true, color: 'bg-orange-600', userCount: 0 },
    { id: '3', name: 'moderator', displayName: 'Moderator', description: 'Manage community and view data', permissions: ['dashboard', 'users.view', 'listings.view', 'orders.view', 'community.moderate'], isSystem: false, color: 'bg-emerald-500', userCount: 0 },
    { id: '4', name: 'editor', displayName: 'Editor', description: 'Create and edit content', permissions: ['dashboard', 'listings.view', 'listings.create', 'listings.edit', 'mcq.view', 'mcq.manage'], isSystem: false, color: 'bg-amber-500', userCount: 0 },
    { id: '5', name: 'viewer', displayName: 'Viewer', description: 'Read-only access', permissions: ['dashboard', 'users.view', 'listings.view', 'orders.view'], isSystem: false, color: 'bg-slate-500', userCount: 0 },
  ];

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault(); setFormLoading(true);
    try {
      const method = editRole ? 'PATCH' : 'POST';
      const body = editRole ? { id: editRole.id, ...form } : { ...form };
      const r = await fetch('/api/admin/roles', { method, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
      const d = await r.json();
      if (d.success || d.id) { setShowDialog(false); setEditRole(null); setForm({ name: '', displayName: '', description: '', permissions: [], color: 'bg-orange-500' }); fetchRoles(); }
      else { setShowDialog(false); setEditRole(null); fetchRoles(); }
    } catch { setShowDialog(false); }
    finally { setFormLoading(false); }
  };

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

  const openEdit = (role: Role) => {
    setEditRole(role);
    setForm({ name: role.name, displayName: role.displayName, description: role.description, permissions: role.permissions, color: role.color });
    setShowDialog(true);
  };

  const togglePermission = (key: string) => {
    setForm(prev => ({
      ...prev,
      permissions: prev.permissions.includes(key) ? prev.permissions.filter(p => p !== key) : [...prev.permissions, key]
    }));
  };

  const permissionGroups = AVAILABLE_PERMISSIONS.reduce((acc, p) => {
    if (!acc[p.group]) acc[p.group] = [];
    acc[p.group].push(p);
    return acc;
  }, {} as Record<string, typeof AVAILABLE_PERMISSIONS>);

  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-6">
      <div className="flex items-center justify-between">
        <div>
          <h3 className="text-lg font-semibold">Role Management</h3>
          <p className="text-sm text-muted-foreground">Create and manage custom roles with granular permissions</p>
        </div>
        <Button className={`gap-2 ${ORANGE_BTN}`} onClick={() => { setEditRole(null); setForm({ name: '', displayName: '', description: '', permissions: [], color: 'bg-orange-500' }); setShowDialog(true); }}>
          <Plus className="h-4 w-4" />Create Role
        </Button>
      </div>

      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
        {roles.map((role) => (
          <Card key={role.id} className="border-0 shadow-sm hover:shadow-md transition-all group">
            <CardContent className="p-5">
              <div className="flex items-start justify-between">
                <div className="flex items-center gap-3">
                  <div className={`flex h-10 w-10 items-center justify-center rounded-xl ${role.color} text-white shadow-sm`}>
                    {role.isSystem ? <Crown className="h-5 w-5" /> : <Shield className="h-5 w-5" />}
                  </div>
                  <div>
                    <h4 className="font-semibold text-sm">{role.displayName}</h4>
                    <p className="text-xs text-muted-foreground">{role.name}</p>
                  </div>
                </div>
                {!role.isSystem && (
                  <div className="flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                    <Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => openEdit(role)}><Pencil className="h-3 w-3" /></Button>
                    <AlertDialog>
                      <AlertDialogTrigger asChild><Button variant="ghost" size="icon" className="h-7 w-7"><Trash2 className="h-3 w-3 text-destructive" /></Button></AlertDialogTrigger>
                      <AlertDialogContent>
                        <AlertDialogHeader><AlertDialogTitle>Delete Role</AlertDialogTitle><AlertDialogDescription>Delete &quot;{role.displayName}&quot; role? Users with this role will be reassigned to Viewer.</AlertDialogDescription></AlertDialogHeader>
                        <AlertDialogFooter><AlertDialogCancel>Cancel</AlertDialogCancel><AlertDialogAction onClick={() => handleDelete(role.id)} className="bg-destructive text-destructive-foreground">Delete</AlertDialogAction></AlertDialogFooter>
                      </AlertDialogContent>
                    </AlertDialog>
                  </div>
                )}
              </div>
              <p className="mt-3 text-xs text-muted-foreground">{role.description}</p>
              <div className="mt-3 flex items-center justify-between">
                <div className="flex items-center gap-1.5">
                  <Users className="h-3.5 w-3.5 text-muted-foreground" />
                  <span className="text-xs text-muted-foreground">{role.userCount} user{role.userCount !== 1 ? 's' : ''}</span>
                </div>
                <Badge variant="outline" className="text-[10px]">{role.permissions.length} permissions</Badge>
              </div>
              <div className="mt-3 flex flex-wrap gap-1">
                {role.permissions.slice(0, 5).map((p) => (
                  <span key={p} className="inline-flex items-center gap-1 rounded-md bg-slate-100 px-1.5 py-0.5 text-[10px] text-slate-600 dark:bg-slate-800 dark:text-slate-400">
                    <Key className="h-2.5 w-2.5" />{p}
                  </span>
                ))}
                {role.permissions.length > 5 && <span className="text-[10px] text-muted-foreground">+{role.permissions.length - 5} more</span>}
              </div>
            </CardContent>
          </Card>
        ))}
      </div>

      <Dialog open={showDialog} onOpenChange={(o) => { setShowDialog(o); if (!o) setEditRole(null); }}>
        <DialogContent className="sm:max-w-[600px] max-h-[85vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2"><Shield className="h-5 w-5 text-orange-500" />{editRole ? 'Edit Role' : 'Create New Role'}</DialogTitle>
            <DialogDescription>Define role name and granular permissions</DialogDescription>
          </DialogHeader>
          <form onSubmit={handleSubmit} className="space-y-4 pt-2">
            <div className="grid grid-cols-2 gap-3">
              <div className="space-y-1.5">
                <Label className="text-xs font-medium">Role Name</Label>
                <Input value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value.replace(/\s/g, '_').toLowerCase() })} placeholder="e.g. content_manager" required />
              </div>
              <div className="space-y-1.5">
                <Label className="text-xs font-medium">Display Name</Label>
                <Input value={form.displayName} onChange={(e) => setForm({ ...form, displayName: e.target.value })} placeholder="e.g. Content Manager" required />
              </div>
            </div>
            <div className="space-y-1.5">
              <Label className="text-xs font-medium">Description</Label>
              <Input value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} placeholder="What this role can do..." />
            </div>
            <div className="space-y-1.5">
              <Label className="text-xs font-medium">Color</Label>
              <div className="flex gap-2">
                {ROLE_COLORS.map((c) => (
                  <button key={c} type="button" onClick={() => setForm({ ...form, color: c })} className={`h-8 w-8 rounded-lg ${c} transition-transform ${form.color === c ? 'scale-110 ring-2 ring-offset-2 ring-orange-500' : 'hover:scale-105'}`} />
                ))}
              </div>
            </div>
            <Separator />
            <div className="space-y-3">
              <div className="flex items-center justify-between">
                <Label className="text-sm font-semibold">Permissions</Label>
                <div className="flex gap-2">
                  <Button type="button" variant="outline" size="sm" className="text-xs h-7" onClick={() => setForm({ ...form, permissions: AVAILABLE_PERMISSIONS.map(p => p.key) })}>
                    <CheckCircle className="mr-1 h-3 w-3" />Select All
                  </Button>
                  <Button type="button" variant="outline" size="sm" className="text-xs h-7" onClick={() => setForm({ ...form, permissions: [] })}>
                    <XCircle className="mr-1 h-3 w-3" />Clear All
                  </Button>
                </div>
              </div>
              {Object.entries(permissionGroups).map(([group, perms]) => (
                <div key={group} className="space-y-2">
                  <h5 className="text-xs font-semibold text-muted-foreground uppercase tracking-wider">{group}</h5>
                  <div className="grid grid-cols-2 gap-2">
                    {perms.map((perm) => (
                      <label key={perm.key} className={`flex items-center gap-2 rounded-lg border px-3 py-2 cursor-pointer transition-all text-xs ${form.permissions.includes(perm.key) ? 'border-orange-500 bg-orange-50 text-orange-700 dark:bg-orange-950/20 dark:text-orange-400' : 'hover:border-slate-300 dark:hover:border-slate-600'}`}>
                        <input type="checkbox" checked={form.permissions.includes(perm.key)} onChange={() => togglePermission(perm.key)} className="sr-only" />
                        <div className={`h-4 w-4 rounded border flex items-center justify-center ${form.permissions.includes(perm.key) ? 'bg-orange-500 border-orange-500' : 'border-slate-300'}`}>
                          {form.permissions.includes(perm.key) && <CheckCircle className="h-3 w-3 text-white" />}
                        </div>
                        {perm.label}
                      </label>
                    ))}
                  </div>
                </div>
              ))}
            </div>
            <Button type="submit" className={`w-full ${ORANGE_BTN} font-semibold`} disabled={formLoading}>
              {formLoading ? 'Saving...' : editRole ? 'Update Role' : 'Create Role'}
            </Button>
          </form>
        </DialogContent>
      </Dialog>
    </div>
  );
}

function Separator() {
  return <div className="border-t border-slate-200 dark:border-slate-700 my-2" />;
}
