import React, { useState, useEffect } from 'react';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Badge } from "@/components/ui/badge";
import { Shield, Save } from "lucide-react";

interface RoleDialogProps {
  isOpen: boolean;
  onOpenChange: (open: boolean) => void;
  role: any;
  onSave: (roleId: string, permissions: string[]) => void;
}

export const RoleDialog: React.FC<RoleDialogProps> = ({
  isOpen,
  onOpenChange,
  role,
  onSave,
}) => {
  const [selectedPermissions, setSelectedPermissions] = useState<string[]>([]);

  useEffect(() => {
    if (role) {
      setSelectedPermissions(role.permissions || []);
    }
  }, [role, isOpen]);

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

  if (!role) return null;

  const permissionSections = [
    {
      title: "Action Permissions",
      color: "from-green-50 to-emerald-50 border-green-200",
      textColor: "text-green-900",
      permissions: [
        { id: "action:approve", label: "Approve Applications" },
        { id: "action:reject", label: "Reject Applications" },
        { id: "action:upload_docs", label: "Upload Documents" },
        { id: "action:request_changes", label: "Request Changes" },
        { id: "action:forward", label: "Forward to Others" },
        { id: "action:reassign", label: "Reassign Applications" },
        { id: "action:schedule_interview", label: "Schedule Interviews" },
        { id: "action:add_comments", label: "Add Comments/Notes" },
        { id: "action:rank_applicants", label: "Rank Applicants" },
        { id: "action:final_approval", label: "Final Approval" },
      ]
    },
    {
      title: "View/Access Permissions",
      color: "from-blue-50 to-cyan-50 border-blue-200",
      textColor: "text-blue-900",
      permissions: [
        { id: "view:view_details", label: "Application Details" },
        { id: "view:view_financial", label: "Financial Information" },
        { id: "view:view_discussions", label: "Discussion Notes" },
        { id: "view:view_progress", label: "Progress Tracking" },
        { id: "view:view_audit", label: "Audit Logs" },
        { id: "view:view_documents", label: "All Documents" },
        { id: "view:view_personal", label: "Personal Information" },
        { id: "view:view_business", label: "Business Details" },
        { id: "view:view_reports", label: "Reports & Analytics" },
        { id: "view:view_history", label: "Application History" },
      ]
    },
    {
      title: "Application Stage Access",
      color: "from-red-50 to-orange-50 border-red-200",
      textColor: "text-red-900",
      permissions: [
        { id: "stage:initial_review", label: "Initial Review" },
        { id: "stage:field_verification", label: "Field Verification" },
        { id: "stage:level1_interview", label: "Level 1 Interview" },
        { id: "stage:level2_interview", label: "Level 2 Interview" },
        { id: "stage:ranking", label: "Ranking & Selection" },
        { id: "stage:legal_review", label: "Legal Review" },
        { id: "stage:financial_review", label: "Financial Review" },
        { id: "stage:final_approval", label: "Final Approval" },
        { id: "stage:payment", label: "Payment Verification" },
        { id: "stage:onboarding", label: "Onboarding" },
      ]
    }
  ];

  return (
    <Dialog open={isOpen} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-lg max-w-3xl max-h-[90vh] overflow-y-auto p-0 gap-0 border-none shadow-2xl custom-scrollbar">
        <DialogHeader className="p-6 pb-2 space-y-2 text-left bg-white sticky top-0 z-10 border-b">
          <DialogTitle className="text-xl font-bold tracking-tight">Edit Role Permissions - {role.name}</DialogTitle>
          <DialogDescription className="text-slate-500 text-sm">
            Configure default permissions for all users assigned to the {role.name} role
          </DialogDescription>
        </DialogHeader>

        <div className="p-6 space-y-6">
          <div className="bg-gradient-to-br from-purple-50 to-indigo-50 rounded-xl p-5 border border-purple-100 shadow-sm">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-4">
                <div className="w-12 h-12 bg-white rounded-xl shadow-sm flex items-center justify-center border border-purple-100">
                  <Shield className="w-6 h-6 text-purple-600" />
                </div>
                <div>
                  <h4 className="text-base font-bold text-slate-900">{role.name}</h4>
                  <p className="text-xs font-medium text-slate-500 uppercase tracking-widest">{role.userCount || 0} users currently assigned</p>
                </div>
              </div>
              <Badge className="bg-purple-600 hover:bg-purple-700 px-3 py-1 rounded-full text-[10px] font-bold tracking-wider uppercase">
                Role Configuration
              </Badge>
            </div>
          </div>

          <div className="space-y-5">
            <h4 className="text-sm font-bold text-slate-800 flex items-center gap-2">
              <span className="w-1.5 h-1.5 bg-red-500 rounded-full"></span>
              Configure Default Permissions
            </h4>
            
            <div className="space-y-4">
              {permissionSections.map((section, sidx) => (
                <div key={sidx} className={`border rounded-xl p-5 bg-gradient-to-br ${section.color} shadow-sm transition-all hover:shadow-md`}>
                  <h5 className={`text-sm font-bold ${section.textColor} mb-4 flex items-center justify-between`}>
                    {section.title}
                    <span className="text-[10px] bg-white/50 px-2 py-0.5 rounded-full opacity-70 italic font-normal">Section {sidx + 1}</span>
                  </h5>
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-y-3 gap-x-6">
                    {section.permissions.map((perm) => (
                      <div key={perm.id} className="flex items-center space-x-3 group cursor-pointer p-1 rounded-md hover:bg-white/40 transition-colors">
                        <Checkbox 
                          id={`perm-${perm.id}`} 
                          checked={selectedPermissions.includes(perm.id)}
                          onCheckedChange={() => togglePermission(perm.id)}
                          className="border-slate-300 data-[state=checked]:bg-purple-600 data-[state=checked]:border-purple-600"
                        />
                        <label 
                          htmlFor={`perm-${perm.id}`}
                          className="text-sm font-medium text-slate-700 cursor-pointer group-hover:text-slate-900 transition-colors flex-1"
                        >
                          {perm.label}
                        </label>
                      </div>
                    ))}
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>

        <div className="flex gap-3 p-6 pt-4 border-t sticky bottom-0 bg-white/80 backdrop-blur-md z-10">
          <Button variant="ghost" onClick={() => onOpenChange(false)} className="flex-1 h-11 font-bold text-slate-600 hover:bg-slate-100">
            Cancel
          </Button>
          <Button 
            onClick={() => onSave(role.id, selectedPermissions)} 
            className="flex-1 h-11 bg-purple-600 hover:bg-purple-700 font-bold text-white shadow-lg shadow-purple-200"
          >
            <Save className="w-4 h-4 mr-2" />
            Save Role Permissions
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  );
};
