'use client';

import React, { useState, useEffect, useCallback } from 'react';
import { useTranslation } from '@/lib/i18n';
import { Shield, Plus, Trash2, Edit3, Save, X, Loader2, Check, ChevronsUpDown } 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, 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 { authFetch } from '@/lib/api';
import DataPagination from '@/components/shared/DataPagination';

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

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

const MODULES = [
  'dashboard', 'tasks', 'users', 'areas', 'engineers', 'hod',
  'vendors', 'workload', 'notifications', 'reports', 'export', 'ai',
  'workflow', 'settings', 'backup', 'role_permission', 'departments', 'gis_tracking',
];

const MODULE_DISPLAY: Record<string, string> = {
  dashboard: 'Dashboard',
  tasks: 'Tasks',
  users: 'Users',
  areas: 'Areas',
  engineers: 'Engineers',
  hod: 'HOD',
  vendors: 'Vendors',
  workload: 'Workload',
  notifications: 'Notifications',
  reports: 'Reports',
  export: 'Export',
  ai: 'AI Agent',
  workflow: 'Workflow',
  settings: 'Settings',
  backup: 'Backup',
  role_permission: 'Role & Permission',
  departments: 'Departments',
  gis_tracking: 'GIS Tracking',
};

const PERM_FIELDS = ['canCreate', 'canRead', 'canUpdate', 'canDelete', 'canView'] as const;
type PermField = typeof PERM_FIELDS[number];

export default function RolePermissionManager() {
  const { t } = useTranslation();
  const [roles, setRoles] = useState<RoleData[]>([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [selectedRole, setSelectedRole] = useState<RoleData | null>(null);
  const [editPermissions, setEditPermissions] = useState<PermissionData[]>([]);
  const [rolePage, setRolePage] = useState(1);
  const ROLES_PER_PAGE = 10;

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

  const fetchRoles = useCallback(async () => {
    setLoading(true);
    try {
      const res = await authFetch('/api/roles');
      if (res.ok) {
        const data = await res.json();
        setRoles(data.roles || []);
        // Auto-select first role only on initial load (when no role is selected)
        if (data.roles?.length > 0) {
          setSelectedRole((prev) => prev || data.roles[0]);
          setEditPermissions((prev) => prev.length > 0 ? prev : (data.roles[0].permissions || []));
        }
      }
    } catch { } finally { setLoading(false); }
  }, []);

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

  const handleSelectRole = (role: RoleData) => {
    setSelectedRole(role);
    setEditPermissions(role.permissions || []);
  };

  const roleTotalPages = Math.ceil(roles.length / ROLES_PER_PAGE);
  const paginatedRoles = roles.slice((rolePage - 1) * ROLES_PER_PAGE, rolePage * ROLES_PER_PAGE);

  const handleCreateRole = async () => {
    if (!newRoleName.trim() || !newRoleDisplayName.trim()) return;
    setSaving(true);
    try {
      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',
        body: JSON.stringify({
          name: newRoleName.trim().toLowerCase().replace(/\s+/g, '_'),
          displayName: newRoleDisplayName.trim(),
          description: newRoleDescription.trim(),
          permissions: defaultPerms,
        }),
      });
      if (res.ok) {
        setCreateDialogOpen(false);
        setNewRoleName('');
        setNewRoleDisplayName('');
        setNewRoleDescription('');
        fetchRoles();
      }
    } catch { } finally { setSaving(false); }
  };

  const handleDeleteRole = async (roleId: string) => {
    setSaving(true);
    try {
      const res = await authFetch(`/api/roles/${roleId}`, { method: 'DELETE' });
      if (res.ok) {
        if (selectedRole?.id === roleId) {
          setSelectedRole(null);
          setEditPermissions([]);
        }
        fetchRoles();
      }
    } catch { } finally { setSaving(false); }
  };

  // FIX: Use module name instead of index for toggling permissions
  const togglePermission = (moduleName: string, field: PermField) => {
    setEditPermissions(prev => {
      const idx = prev.findIndex(p => p.module === moduleName);
      if (idx >= 0) {
        // Update existing permission
        const updated = [...prev];
        updated[idx] = { ...updated[idx], [field]: !updated[idx][field] };
        return updated;
      } else {
        // Create new permission entry for this module
        const newPerm: PermissionData = {
          id: '',
          roleId: selectedRole?.id || '',
          module: moduleName,
          canCreate: false,
          canRead: true,
          canUpdate: false,
          canDelete: false,
          canView: true,
        };
        // Toggle the specific field: default for canRead/canView is true, so toggle to false
        newPerm[field] = !(field === 'canRead' || field === 'canView');
        return [...prev, newPerm];
      }
    });
  };

  const savePermissions = async () => {
    if (!selectedRole) return;
    setSaving(true);
    try {
      // Ensure all modules have permission entries
      const allPerms = MODULES.map((mod) => {
        const existing = editPermissions.find(p => p.module === mod);
        return existing || { module: mod, canCreate: false, canRead: true, canUpdate: false, canDelete: false, canView: true };
      });
      const res = await authFetch(`/api/roles/${selectedRole.id}`, {
        method: 'PUT',
        body: JSON.stringify({ permissions: allPerms }),
      });
      if (res.ok) {
        fetchRoles();
      }
    } catch { } finally { setSaving(false); }
  };

  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">
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-foreground">Role & Permission Manager</h1>
          <p className="text-sm text-muted-foreground mt-1">Create roles and configure module-level permissions</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>

      <div className="grid grid-cols-1 lg:grid-cols-4 gap-4">
        {/* Role List */}
        <Card className="lg:col-span-1">
          <CardHeader className="pb-2">
            <CardTitle className="text-base">Roles</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-1 max-h-96 overflow-y-auto">
              {paginatedRoles.map((role) => (
                <div
                  key={role.id}
                  onClick={() => handleSelectRole(role)}
                  className={`flex items-center justify-between p-2.5 rounded-lg cursor-pointer transition-colors ${
                    selectedRole?.id === role.id ? 'bg-emerald-100 dark:bg-emerald-900/30 text-emerald-800 dark:text-emerald-200' : 'hover:bg-accent/50'
                  }`}
                >
                  <div className="min-w-0">
                    <p className="text-sm font-medium truncate">{role.displayName}</p>
                    <p className="text-xs text-muted-foreground">{role.name}</p>
                  </div>
                  <div className="flex items-center gap-1.5">
                    {role.isSystem && <Badge variant="outline" className="text-[9px]">System</Badge>}
                    {!role.isSystem && (
                      <button onClick={(e) => { e.stopPropagation(); handleDeleteRole(role.id); }} className="text-muted-foreground hover:text-red-500">
                        <Trash2 className="w-3.5 h-3.5" />
                      </button>
                    )}
                  </div>
                </div>
              ))}
            </div>
            <DataPagination
              page={rolePage}
              totalPages={roleTotalPages}
              total={roles.length}
              onPageChange={setRolePage}
              limit={ROLES_PER_PAGE}
            />
          </CardContent>
        </Card>

        {/* Permission Matrix */}
        <Card className="lg:col-span-3">
          <CardHeader className="pb-2">
            <CardTitle className="text-base flex items-center gap-2">
              <Shield className="w-4 h-4 text-emerald-600" />
              {selectedRole ? `Permissions: ${selectedRole.displayName}` : 'Select a role'}
            </CardTitle>
            <CardDescription>Configure CRUD+View permissions per module</CardDescription>
          </CardHeader>
          <CardContent>
            {selectedRole ? (
              <>
                <div className="overflow-x-auto">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead className="text-xs w-48">Module</TableHead>
                        <TableHead className="text-xs text-center">Create</TableHead>
                        <TableHead className="text-xs text-center">Read</TableHead>
                        <TableHead className="text-xs text-center">Update</TableHead>
                        <TableHead className="text-xs text-center">Delete</TableHead>
                        <TableHead className="text-xs text-center">View</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {MODULES.map((mod) => {
                        const perm = editPermissions.find(p => p.module === mod);
                        return (
                          <TableRow key={mod}>
                            <TableCell className="text-sm font-medium">{MODULE_DISPLAY[mod] || mod.replace(/_/g, ' ')}</TableCell>
                            {PERM_FIELDS.map((field) => (
                              <TableCell key={field} className="text-center">
                                <button
                                  onClick={() => togglePermission(mod, field)}
                                  className={`w-7 h-7 rounded-md flex items-center justify-center transition-colors ${
                                    perm?.[field] ? 'bg-emerald-100 text-emerald-600 dark:bg-emerald-900/30 dark:text-emerald-300' : 'bg-gray-100 text-gray-400 dark:bg-gray-800 dark:text-gray-500'
                                  }`}
                                >
                                  {perm?.[field] ? <Check className="w-4 h-4" /> : <X className="w-3 h-3" />}
                                </button>
                              </TableCell>
                            ))}
                          </TableRow>
                        );
                      })}
                    </TableBody>
                  </Table>
                </div>
                <div className="mt-4 flex justify-end">
                  <Button className="bg-emerald-600 hover:bg-emerald-700" onClick={savePermissions} disabled={saving}>
                    {saving ? <Loader2 className="w-4 h-4 animate-spin mr-1" /> : <Save className="w-4 h-4 mr-1" />}
                    Save Permissions
                  </Button>
                </div>
              </>
            ) : (
              <div className="py-12 text-center text-muted-foreground">
                <Shield className="w-12 h-12 mx-auto mb-3 opacity-20" />
                <p className="text-sm">Select a role to manage its permissions</p>
              </div>
            )}
          </CardContent>
        </Card>
      </div>

      {/* Create Role Dialog */}
      <Dialog open={createDialogOpen} onOpenChange={setCreateDialogOpen}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>Create New Role</DialogTitle>
          </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" />
            </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>
    </div>
  );
}
