'use client';

import React, { useState, useEffect, useCallback } from 'react';
import { useTranslation } from '@/lib/i18n';
import { Shield, Save, Loader2, Check, X, Lock } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
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[];
}

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];

const PERM_LABELS: Record<PermField, string> = {
  canCreate: 'Create',
  canRead: 'Read',
  canUpdate: 'Update',
  canDelete: 'Delete',
  canView: 'View',
};

export default function PermissionManager() {
  const { t } = useTranslation();
  const { toast } = useToast();
  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 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)
        setSelectedRole((prev) => {
          if (!prev && data.roles?.length > 0) {
            return data.roles[0];
          }
          return prev;
        });
        // Set edit permissions for initial role selection (moved outside setSelectedRole updater)
        setEditPermissions((prev) => {
          if (prev.length === 0 && data.roles?.length > 0) {
            return data.roles[0].permissions || [];
          }
          return prev;
        });
      }
    } catch { } finally { setLoading(false); }
  }, []);

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

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

  const togglePermission = (moduleName: string, field: PermField) => {
    setEditPermissions(prev => {
      const idx = prev.findIndex(p => p.module === moduleName);
      if (idx >= 0) {
        const updated = [...prev];
        updated[idx] = { ...updated[idx], [field]: !updated[idx][field] };
        return updated;
      } else {
        const newPerm: PermissionData = {
          id: '',
          roleId: selectedRole?.id || '',
          module: moduleName,
          canCreate: false,
          canRead: true,
          canUpdate: false,
          canDelete: false,
          canView: true,
        };
        newPerm[field] = !newPerm[field];
        return [...prev, newPerm];
      }
    });
  };

  const toggleAllForModule = (moduleName: string, value: boolean) => {
    setEditPermissions(prev => {
      const idx = prev.findIndex(p => p.module === moduleName);
      if (idx >= 0) {
        const updated = [...prev];
        updated[idx] = {
          ...updated[idx],
          canCreate: value,
          canRead: value,
          canUpdate: value,
          canDelete: value,
          canView: value,
        };
        return updated;
      } else {
        return [...prev, {
          id: '',
          roleId: selectedRole?.id || '',
          module: moduleName,
          canCreate: value,
          canRead: value,
          canUpdate: value,
          canDelete: value,
          canView: value,
        }];
      }
    });
  };

  const savePermissions = async () => {
    if (!selectedRole) return;
    setSaving(true);
    try {
      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',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ permissions: allPerms }),
      });
      if (res.ok) {
        toast({ title: 'Permissions saved successfully' });
        fetchRoles();
      } else {
        const err = await res.json();
        toast({ title: 'Error saving permissions', description: err.error || 'Unknown error', variant: 'destructive' });
      }
    } catch {
      toast({ title: 'Network error', variant: 'destructive' });
    } finally { setSaving(false); }
  };

  const getModulePermCount = (role: RoleData) => {
    return role.permissions ? role.permissions.filter(p => p.canRead || p.canCreate || p.canUpdate || p.canDelete || p.canView).length : 0;
  };

  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">
            <Lock className="w-6 h-6 text-emerald-600" />
            Permissions
          </h1>
          <p className="text-sm text-muted-foreground mt-1">Configure module-level CRUD permissions for each role</p>
        </div>
        {selectedRole && (
          <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="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">Select Role</CardTitle>
            <CardDescription className="text-xs">Choose a role to configure permissions</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="space-y-1 max-h-96 overflow-y-auto">
              {roles.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>
                  <Badge variant="secondary" className="text-[9px] ml-2 flex-shrink-0">
                    {getModulePermCount(role)} mods
                  </Badge>
                </div>
              ))}
            </div>
          </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>Click cells to toggle permissions. Click module name to toggle all.</CardDescription>
          </CardHeader>
          <CardContent>
            {selectedRole ? (
              <>
                <div className="overflow-x-auto">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead className="text-xs w-48">Module</TableHead>
                        {PERM_FIELDS.map(field => (
                          <TableHead key={field} className="text-xs text-center">{PERM_LABELS[field]}</TableHead>
                        ))}
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {MODULES.map((mod) => {
                        const perm = editPermissions.find(p => p.module === mod);
                        const allEnabled = PERM_FIELDS.every(f => perm?.[f]);
                        return (
                          <TableRow key={mod}>
                            <TableCell className="text-sm font-medium">
                              <button
                                onClick={() => toggleAllForModule(mod, !allEnabled)}
                                className="hover:text-emerald-600 transition-colors text-left"
                              >
                                {MODULE_DISPLAY[mod] || mod.replace(/_/g, ' ')}
                              </button>
                            </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 items-center justify-between">
                  <p className="text-xs text-muted-foreground">
                    {editPermissions.filter(p => p.canCreate || p.canRead || p.canUpdate || p.canDelete || p.canView).length} of {MODULES.length} modules configured
                  </p>
                  <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>
    </div>
  );
}
