import React, { useEffect, useState } from 'react';
import { useAuth } from '../../context/AuthContext';
import api from '../../utils/api';
import { Card } from '../../components/ui/card';
import { Button } from '../../components/ui/button';
import { Checkbox } from '../../components/ui/checkbox';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../../components/ui/tabs';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '../../components/ui/alert-dialog';
import { toast } from 'sonner';
import { Shield, Save, Lock, ChevronDown, ChevronUp } from 'lucide-react';

const AdminPermissions = () => {
  const { hasPermission } = useAuth();
  const [permissions, setPermissions] = useState([]);
  const [rolePermissions, setRolePermissions] = useState({
    admin: [],
    member: [],
    guest: []
  });
  const [selectedPermissions, setSelectedPermissions] = useState({
    admin: [],
    member: [],
    guest: []
  });
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [showConfirmDialog, setShowConfirmDialog] = useState(false);
  const [selectedRole, setSelectedRole] = useState('admin');
  const [expandedModules, setExpandedModules] = useState({});
  const [hasChanges, setHasChanges] = useState(false);

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

  useEffect(() => {
    // Check if there are unsaved changes
    const changed = ['admin', 'member', 'guest'].some(role => {
      const current = selectedPermissions[role].slice().sort();
      const original = rolePermissions[role].slice().sort();
      return JSON.stringify(current) !== JSON.stringify(original);
    });
    setHasChanges(changed);
  }, [selectedPermissions, rolePermissions]);

  const fetchPermissions = async () => {
    try {
      // Fetch all permissions
      const permsResponse = await api.get('/admin/permissions');
      setPermissions(permsResponse.data);

      // Fetch permissions for each role
      const roles = ['admin', 'member', 'guest'];
      const rolePermsData = {};
      const selectedPermsData = {};

      for (const role of roles) {
        const response = await api.get(`/admin/permissions/roles/${role}`);
        rolePermsData[role] = response.data.map(p => p.code);
        selectedPermsData[role] = response.data.map(p => p.code);
      }

      setRolePermissions(rolePermsData);
      setSelectedPermissions(selectedPermsData);

      // Expand all modules by default
      const modules = [...new Set(permsResponse.data.map(p => p.module))];
      const expanded = {};
      modules.forEach(module => {
        expanded[module] = true;
      });
      setExpandedModules(expanded);
    } catch (error) {
      toast.error('Failed to fetch permissions');
    } finally {
      setLoading(false);
    }
  };

  const togglePermission = (role, permissionCode) => {
    setSelectedPermissions(prev => {
      const current = prev[role] || [];
      if (current.includes(permissionCode)) {
        return {
          ...prev,
          [role]: current.filter(p => p !== permissionCode)
        };
      } else {
        return {
          ...prev,
          [role]: [...current, permissionCode]
        };
      }
    });
  };

  const toggleModule = (role, module) => {
    const modulePerms = permissions
      .filter(p => p.module === module)
      .map(p => p.code);

    const allSelected = modulePerms.every(code =>
      selectedPermissions[role].includes(code)
    );

    if (allSelected) {
      // Deselect all module permissions
      setSelectedPermissions(prev => ({
        ...prev,
        [role]: prev[role].filter(p => !modulePerms.includes(p))
      }));
    } else {
      // Select all module permissions
      setSelectedPermissions(prev => ({
        ...prev,
        [role]: [...new Set([...prev[role], ...modulePerms])]
      }));
    }
  };

  const handleSave = () => {
    setShowConfirmDialog(true);
  };

  const confirmSave = async () => {
    setSaving(true);
    setShowConfirmDialog(false);

    try {
      // Save permissions for each role
      await Promise.all([
        api.put(`/admin/permissions/roles/${selectedRole}`, {
          permission_codes: selectedPermissions[selectedRole]
        })
      ]);

      // Update original state
      setRolePermissions(prev => ({
        ...prev,
        [selectedRole]: [...selectedPermissions[selectedRole]]
      }));

      toast.success(`Permissions updated for ${selectedRole}`);
    } catch (error) {
      toast.error(error.response?.data?.detail || 'Failed to update permissions');
    } finally {
      setSaving(false);
    }
  };

  const toggleModuleExpansion = (module) => {
    setExpandedModules(prev => ({
      ...prev,
      [module]: !prev[module]
    }));
  };

  const groupedPermissions = permissions.reduce((acc, perm) => {
    if (!acc[perm.module]) {
      acc[perm.module] = [];
    }
    acc[perm.module].push(perm);
    return acc;
  }, {});

  const getModuleProgress = (role, module) => {
    const modulePerms = groupedPermissions[module] || [];
    const selected = modulePerms.filter(p =>
      selectedPermissions[role].includes(p.code)
    ).length;
    return `${selected}/${modulePerms.length}`;
  };

  const isModuleFullySelected = (role, module) => {
    const modulePerms = groupedPermissions[module] || [];
    return modulePerms.every(p => selectedPermissions[role].includes(p.code));
  };

  const getRoleBadge = (role) => {
    const config = {
      admin: { label: 'Admin', color: 'bg-[var(--green-light)]', icon: Shield },
      member: { label: 'Member', color: 'bg-brand-purple ', icon: Shield },
      guest: { label: 'Guest', color: 'bg-gray-400', icon: Shield }
    };

    const roleConfig = config[role] || config.admin;
    const Icon = roleConfig.icon;

    return (
      <div className={`inline-flex items-center gap-2 ${roleConfig.color} text-white px-4 py-2 rounded-full`}>
        <Icon className="h-4 w-4" />
        <span className="font-semibold">{roleConfig.label}</span>
      </div>
    );
  };

  if (loading) {
    return (
      <div className="text-center py-20">
        <p className="text-brand-purple " style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
          Loading permissions...
        </p>
      </div>
    );
  }

  if (!hasPermission('permissions.assign')) {
    return (
      <div className="text-center py-20">
        <Lock className="h-20 w-20 text-red-500 mx-auto mb-6" />
        <h2 className="text-3xl font-semibold text-[var(--purple-ink)] mb-4" style={{ fontFamily: "'Inter', sans-serif" }}>
          Access Denied
        </h2>
        <p className="text-lg text-brand-purple " style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
          You don't have permission to manage role permissions.
        </p>
        <p className="text-sm text-gray-500 mt-2">
          Only Superadmins can access this page.
        </p>
      </div>
    );
  }

  return (
    <>
      <div className="mb-8">
        <h1 className="text-4xl md:text-5xl font-semibold text-[var(--purple-ink)] mb-4" style={{ fontFamily: "'Inter', sans-serif" }}>
          Permission Management
        </h1>
        <p className="text-lg text-brand-purple " style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
          Configure granular permissions for each role. Superadmin always has all permissions.
        </p>
      </div>

      {/* Role Tabs */}
      <Tabs value={selectedRole} onValueChange={setSelectedRole} className="mb-8">
        <TabsList className="grid w-full grid-cols-3 mb-8">
          <TabsTrigger value="admin" className="text-lg py-3">
            {getRoleBadge('admin')}
          </TabsTrigger>
          <TabsTrigger value="member" className="text-lg py-3">
            {getRoleBadge('member')}
          </TabsTrigger>
          <TabsTrigger value="guest" className="text-lg py-3">
            {getRoleBadge('guest')}
          </TabsTrigger>
        </TabsList>

        {['admin', 'member', 'guest'].map(role => (
          <TabsContent key={role} value={role}>
            {/* Stats */}
            <div className="grid md:grid-cols-3 gap-4 mb-8">
              <Card className="p-6 bg-background rounded-2xl border border-[var(--neutral-800)]">
                <p className="text-sm text-brand-purple  mb-2" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                  Total Permissions
                </p>
                <p className="text-3xl font-semibold text-[var(--purple-ink)]" style={{ fontFamily: "'Inter', sans-serif" }}>
                  {permissions.length}
                </p>
              </Card>
              <Card className="p-6 bg-background rounded-2xl border border-[var(--neutral-800)]">
                <p className="text-sm text-brand-purple  mb-2" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                  Assigned
                </p>
                <p className="text-3xl font-semibold text-[var(--purple-ink)]" style={{ fontFamily: "'Inter', sans-serif" }}>
                  {selectedPermissions[role].length}
                </p>
              </Card>
              <Card className="p-6 bg-background rounded-2xl border border-[var(--neutral-800)]">
                <p className="text-sm text-brand-purple  mb-2" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                  Modules
                </p>
                <p className="text-3xl font-semibold text-[var(--purple-ink)]" style={{ fontFamily: "'Inter', sans-serif" }}>
                  {Object.keys(groupedPermissions).length}
                </p>
              </Card>
            </div>

            {/* Permissions by Module */}
            <div className="space-y-4">
              {Object.entries(groupedPermissions).map(([module, perms]) => (
                <Card key={module} className="bg-background rounded-2xl border border-[var(--neutral-800)] overflow-hidden">
                  {/* Module Header */}
                  <div
                    className="p-6 bg-gradient-to-r from-[var(--neutral-800)] to-white cursor-pointer hover:from-[var(--neutral-600)] transition-colors"
                    onClick={() => toggleModuleExpansion(module)}
                  >
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-4">
                        <Checkbox
                          checked={isModuleFullySelected(role, module)}
                          onCheckedChange={() => toggleModule(role, module)}
                          onClick={(e) => e.stopPropagation()}
                          className="h-6 w-6 border-2 border-brand-purple  data-[state=checked]:bg-brand-purple "
                        />
                        <div>
                          <h3 className="text-xl font-semibold text-[var(--purple-ink)] capitalize" style={{ fontFamily: "'Inter', sans-serif" }}>
                            {module}
                          </h3>
                          <p className="text-sm text-brand-purple " style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                            {getModuleProgress(role, module)} permissions
                          </p>
                        </div>
                      </div>
                      {expandedModules[module] ? (
                        <ChevronUp className="h-6 w-6 text-brand-purple " />
                      ) : (
                        <ChevronDown className="h-6 w-6 text-brand-purple " />
                      )}
                    </div>
                  </div>

                  {/* Module Permissions */}
                  {expandedModules[module] && (
                    <div className="p-6 pt-0">
                      <div className="grid md:grid-cols-2 gap-4 mt-4">
                        {perms.map(perm => (
                          <div
                            key={perm.code}
                            className="flex items-start gap-4 p-4 rounded-xl hover:bg-[var(--lavender-700)] transition-colors border border-transparent hover:border-[var(--neutral-800)]"
                          >
                            <Checkbox
                              checked={selectedPermissions[role].includes(perm.code)}
                              onCheckedChange={() => togglePermission(role, perm.code)}
                              className="mt-1 h-5 w-5 border-2 border-brand-purple  data-[state=checked]:bg-brand-purple "
                            />
                            <div className="flex-1">
                              <p className="font-semibold text-[var(--purple-ink)] mb-1" style={{ fontFamily: "'Inter', sans-serif" }}>
                                {perm.name}
                              </p>
                              <p className="text-sm text-brand-purple " style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                                {perm.description}
                              </p>
                              <p className="text-xs text-gray-400 mt-1 font-mono">
                                {perm.code}
                              </p>
                            </div>
                          </div>
                        ))}
                      </div>
                    </div>
                  )}
                </Card>
              ))}
            </div>
          </TabsContent>
        ))}
      </Tabs>

      {/* Superadmin Note */}
      <Card className="p-6 bg-gradient-to-r from-brand-purple  to-[var(--purple-ink)] rounded-2xl border-none mb-8">
        <div className="flex items-start gap-4">
          <Lock className="h-6 w-6 text-white flex-shrink-0 mt-1" />
          <div className="text-white">
            <p className="font-semibold mb-2" style={{ fontFamily: "'Inter', sans-serif" }}>
              Superadmin Permissions
            </p>
            <p className="text-sm" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
              Superadmins automatically have all permissions and cannot be restricted. This ensures you can never lock yourself out of the system.
            </p>
          </div>
        </div>
      </Card>

      {/* Save Button */}
      {hasChanges && (
        <div className="fixed bottom-8 right-8 z-50">
          <Button
            onClick={handleSave}
            disabled={saving}
            className="h-14 px-8 bg-[var(--green-light)] hover:bg-[var(--green-fern)] text-white rounded-full shadow-lg text-lg font-semibold"
          >
            <Save className="h-5 w-5 mr-2" />
            {saving ? 'Saving...' : 'Save Changes'}
          </Button>
        </div>
      )}

      {/* Confirmation Dialog */}
      <AlertDialog open={showConfirmDialog} onOpenChange={setShowConfirmDialog}>
        <AlertDialogContent className="rounded-2xl">
          <AlertDialogHeader>
            <AlertDialogTitle className="text-2xl text-[var(--purple-ink)]" style={{ fontFamily: "'Inter', sans-serif" }}>
              Confirm Permission Changes
            </AlertDialogTitle>
            <AlertDialogDescription className="text-brand-purple " style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
              Are you sure you want to update permissions for <span className="font-semibold capitalize">{selectedRole}</span>?
              This will immediately affect all users with this role.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel className="rounded-xl">Cancel</AlertDialogCancel>
            <AlertDialogAction
              onClick={confirmSave}
              className="rounded-xl bg-[var(--green-light)] hover:bg-[var(--green-fern)] text-white"
            >
              Confirm
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
};

export default AdminPermissions;
