'use client';

import React, { useState, useEffect, useCallback } from 'react';
import { useTranslation } from '@/lib/i18n';
import { Shield, Plus, Trash2, Edit3, Save, X, Loader2, Check, Users } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog';
import { Textarea } from '@/components/ui/textarea';
import { Switch } from '@/components/ui/switch';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { useToast } from '@/hooks/use-toast';
import { authFetch } from '@/lib/api';

interface RoleData {
  id: string;
  name: string;
  displayName: string;
  description: string | null;
  isSystem: boolean;
  isActive: boolean;
  permissions: PermissionData[];
  _count?: { permissions: number };
}

interface PermissionData {
  id: string;
  roleId: string;
  module: string;
  canCreate: boolean;
  canRead: boolean;
  canUpdate: boolean;
  canDelete: boolean;
  canView: boolean;
}

export default function RoleManager() {
  const { t } = useTranslation();
  const { toast } = useToast();
  const [roles, setRoles] = useState<RoleData[]>([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);

  // Create dialog state
  const [createDialogOpen, setCreateDialogOpen] = useState(false);
  const [newRoleName, setNewRoleName] = useState('');
  const [newRoleDisplayName, setNewRoleDisplayName] = useState('');
  const [newRoleDescription, setNewRoleDescription] = useState('');

  // Edit dialog state
  const [editDialogOpen, setEditDialogOpen] = useState(false);
  const [editRole, setEditRole] = useState<RoleData | null>(null);
  const [editDisplayName, setEditDisplayName] = useState('');
  const [editDescription, setEditDescription] = useState('');
  const [editIsActive, setEditIsActive] = useState(true);

  const fetchRoles = useCallback(async () => {
    setLoading(true);
    try {
      const res = await authFetch('/api/roles');
      if (res.ok) {
        const data = await res.json();
        setRoles(data.roles || []);
      }
    } catch { } finally { setLoading(false); }
  }, []);

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

  const handleCreateRole = async () => {
    if (!newRoleName.trim() || !newRoleDisplayName.trim()) return;
    setSaving(true);
    try {
      const MODULES = [
        'dashboard', 'tasks', 'users', 'areas', 'engineers', 'hod',
        'vendors', 'workload', 'notifications', 'reports', 'export', 'ai',
        'workflow', 'settings', 'backup', 'roles', 'departments', 'gis',
      ];
      const defaultPerms = MODULES.map(m => ({ module: m, canRead: true, canView: true, canCreate: false, canUpdate: false, canDelete: false }));
      const res = await authFetch('/api/roles', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: newRoleName.trim().toLowerCase().replace(/\s+/g, '_'),
          displayName: newRoleDisplayName.trim(),
          description: newRoleDescription.trim(),
          permissions: defaultPerms,
        }),
      });
      if (res.ok) {
        toast({ title: 'Role created successfully' });
        setCreateDialogOpen(false);
        setNewRoleName('');
        setNewRoleDisplayName('');
        setNewRoleDescription('');
        fetchRoles();
      } else {
        const err = await res.json();
        toast({ title: 'Error creating role', description: err.error || 'Unknown error', variant: 'destructive' });
      }
    } catch {
      toast({ title: 'Network error', variant: 'destructive' });
    } finally { setSaving(false); }
  };

  const handleEditRole = (role: RoleData) => {
    setEditRole(role);
    setEditDisplayName(role.displayName);
    setEditDescription(role.description || '');
    setEditIsActive(role.isActive);
    setEditDialogOpen(true);
  };

  const handleUpdateRole = async () => {
    if (!editRole) return;
    setSaving(true);
    try {
      const res = await authFetch(`/api/roles/${editRole.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          displayName: editDisplayName,
          description: editDescription,
          isActive: editIsActive,
        }),
      });
      if (res.ok) {
        toast({ title: 'Role updated successfully' });
        setEditDialogOpen(false);
        setEditRole(null);
        fetchRoles();
      } else {
        const err = await res.json();
        toast({ title: 'Error updating role', description: err.error || 'Unknown error', variant: 'destructive' });
      }
    } catch {
      toast({ title: 'Network error', variant: 'destructive' });
    } finally { setSaving(false); }
  };

  const handleDeleteRole = async (roleId: string) => {
    if (!confirm('Are you sure you want to delete this role?')) return;
    setSaving(true);
    try {
      const res = await authFetch(`/api/roles/${roleId}`, { method: 'DELETE' });
      if (res.ok) {
        toast({ title: 'Role deleted successfully' });
        fetchRoles();
      } else {
        const err = await res.json();
        toast({ title: 'Error deleting role', description: err.error || 'Unknown error', variant: 'destructive' });
      }
    } catch {
      toast({ title: 'Network error', variant: 'destructive' });
    } finally { setSaving(false); }
  };

  const getRoleBadgeColor = (roleName: string) => {
    const colors: Record<string, string> = {
      super_admin: 'bg-purple-100 text-purple-800 dark:bg-purple-950/30 dark:text-purple-300',
      admin: 'bg-emerald-100 text-emerald-800 dark:bg-emerald-950/30 dark:text-emerald-300',
      head_of_department: 'bg-blue-100 text-blue-800 dark:bg-blue-950/30 dark:text-blue-300',
      service_engineer: 'bg-orange-100 text-orange-800 dark:bg-orange-950/30 dark:text-orange-300',
      vendor: 'bg-cyan-100 text-cyan-800 dark:bg-cyan-950/30 dark:text-cyan-300',
      user: 'bg-gray-100 text-gray-800 dark:bg-gray-950/30 dark:text-gray-300',
    };
    return colors[roleName] || 'bg-gray-100 text-gray-800';
  };

  if (loading) {
    return <div className="flex items-center justify-center py-20"><Loader2 className="w-8 h-8 animate-spin text-emerald-600" /></div>;
  }

  return (
    <div className="space-y-6 animate-fade-in">
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-foreground flex items-center gap-2">
            <Shield className="w-6 h-6 text-emerald-600" />
            User Roles
          </h1>
          <p className="text-sm text-muted-foreground mt-1">Create, edit, and manage system roles</p>
        </div>
        <Button className="bg-emerald-600 hover:bg-emerald-700" onClick={() => setCreateDialogOpen(true)}>
          <Plus className="w-4 h-4 mr-1" /> Create Role
        </Button>
      </div>

      {/* Roles Table */}
      <Card>
        <CardContent className="p-0">
          {roles.length === 0 ? (
            <div className="p-8 text-center text-muted-foreground">
              <Shield className="w-12 h-12 mx-auto mb-3 opacity-20" />
              <p className="text-sm">No roles found</p>
            </div>
          ) : (
            <div className="overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className="text-xs">Role Name</TableHead>
                    <TableHead className="text-xs">Display Name</TableHead>
                    <TableHead className="text-xs hidden sm:table-cell">Description</TableHead>
                    <TableHead className="text-xs">Type</TableHead>
                    <TableHead className="text-xs">Status</TableHead>
                    <TableHead className="text-xs hidden md:table-cell">Permissions</TableHead>
                    <TableHead className="text-xs">Actions</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {roles.map((role) => (
                    <TableRow key={role.id}>
                      <TableCell>
                        <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-medium ${getRoleBadgeColor(role.name)}`}>
                          {role.name}
                        </span>
                      </TableCell>
                      <TableCell className="text-sm font-medium">{role.displayName}</TableCell>
                      <TableCell className="text-xs text-muted-foreground hidden sm:table-cell max-w-[200px] truncate">
                        {role.description || '-'}
                      </TableCell>
                      <TableCell>
                        {role.isSystem ? (
                          <Badge variant="outline" className="text-[9px] bg-blue-50 text-blue-700 dark:bg-blue-950/30 dark:text-blue-300">System</Badge>
                        ) : (
                          <Badge variant="outline" className="text-[9px] bg-gray-50 text-gray-700 dark:bg-gray-950/30 dark:text-gray-300">Custom</Badge>
                        )}
                      </TableCell>
                      <TableCell>
                        <Badge variant={role.isActive ? "default" : "secondary"} className={`text-[9px] ${role.isActive ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-950/30 dark:text-emerald-300' : 'bg-red-100 text-red-700 dark:bg-red-950/30 dark:text-red-300'}`}>
                          {role.isActive ? 'Active' : 'Inactive'}
                        </Badge>
                      </TableCell>
                      <TableCell className="text-xs hidden md:table-cell">
                        <Badge variant="secondary" className="text-[9px]">{role.permissions?.length || 0} modules</Badge>
                      </TableCell>
                      <TableCell>
                        <div className="flex items-center gap-1">
                          <Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => handleEditRole(role)}>
                            <Edit3 className="w-3.5 h-3.5" />
                          </Button>
                          {!role.isSystem && (
                            <Button variant="ghost" size="icon" className="h-7 w-7 text-red-500 hover:text-red-700" onClick={() => handleDeleteRole(role.id)}>
                              <Trash2 className="w-3.5 h-3.5" />
                            </Button>
                          )}
                        </div>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Create Role Dialog */}
      <Dialog open={createDialogOpen} onOpenChange={setCreateDialogOpen}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>Create New Role</DialogTitle>
            <DialogDescription>Define a new role with a unique name and display name</DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label>Role Name (unique identifier)</Label>
              <Input value={newRoleName} onChange={(e) => setNewRoleName(e.target.value)} placeholder="e.g., area_manager" />
              <p className="text-[10px] text-muted-foreground">Lowercase, spaces will be replaced with underscores</p>
            </div>
            <div className="space-y-2">
              <Label>Display Name</Label>
              <Input value={newRoleDisplayName} onChange={(e) => setNewRoleDisplayName(e.target.value)} placeholder="e.g., Area Manager" />
            </div>
            <div className="space-y-2">
              <Label>Description</Label>
              <Textarea value={newRoleDescription} onChange={(e) => setNewRoleDescription(e.target.value)} placeholder="Role description..." rows={2} />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setCreateDialogOpen(false)}>Cancel</Button>
            <Button className="bg-emerald-600 hover:bg-emerald-700" onClick={handleCreateRole} disabled={!newRoleName.trim() || !newRoleDisplayName.trim() || saving}>
              {saving ? <Loader2 className="w-4 h-4 animate-spin mr-1" /> : <Plus className="w-4 h-4 mr-1" />}
              Create Role
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Edit Role Dialog */}
      <Dialog open={editDialogOpen} onOpenChange={setEditDialogOpen}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>Edit Role: {editRole?.displayName}</DialogTitle>
            <DialogDescription>Update role details</DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label>Display Name</Label>
              <Input value={editDisplayName} onChange={(e) => setEditDisplayName(e.target.value)} />
            </div>
            <div className="space-y-2">
              <Label>Description</Label>
              <Textarea value={editDescription} onChange={(e) => setEditDescription(e.target.value)} rows={2} />
            </div>
            <div className="flex items-center gap-3">
              <Switch checked={editIsActive} onCheckedChange={setEditIsActive} />
              <Label>Active</Label>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setEditDialogOpen(false)}>Cancel</Button>
            <Button className="bg-emerald-600 hover:bg-emerald-700" onClick={handleUpdateRole} disabled={saving}>
              {saving ? <Loader2 className="w-4 h-4 animate-spin mr-1" /> : <Save className="w-4 h-4 mr-1" />}
              Save Changes
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
