
import React, { useState, useEffect } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"; // Added AvatarImage
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { 
  Users, Calendar, Package, DollarSign, FileText, BarChart3, 
  Shield, Building2, Briefcase, Info, ExternalLink 
} from "lucide-react";

const ROLE_TEMPLATES = {
  admin: { name: "Administrator", color: "bg-red-100 text-red-700" },
  procurement: { name: "Procurement Manager", color: "bg-purple-100 text-purple-700" },
  operator: { name: "Operator", color: "bg-blue-100 text-blue-700" },
  sector: { name: "Sector Manager", color: "bg-cyan-100 text-cyan-700" },
  client: { name: "Client", color: "bg-green-100 text-green-700" },
  vendor: { name: "Vendor Partner", color: "bg-amber-100 text-amber-700" },
  workforce: { name: "Workforce Member", color: "bg-slate-100 text-slate-700" }
};

const ROLE_PERMISSIONS = {
  admin: [
    { id: "system_admin", icon: Shield, name: "System Administration", description: "Full access to all system settings and user management", defaultEnabled: true },
    { id: "enterprise_mgmt", icon: Building2, name: "Enterprise Management", description: "Create and manage enterprises, sectors, and partners", defaultEnabled: true },
    { id: "vendor_oversight", icon: Package, name: "Vendor Oversight", description: "Approve/suspend vendors and manage all vendor relationships", defaultEnabled: true },
    { id: "financial_admin", icon: DollarSign, name: "Financial Administration", description: "Access all financial data and process payments", defaultEnabled: true },
    { id: "reports_admin", icon: BarChart3, name: "Admin Reports", description: "Generate and export all system reports", defaultEnabled: true },
  ],
  procurement: [
    { id: "vendor_view", icon: Package, name: "View All Vendors", description: "Access complete vendor directory and profiles", defaultEnabled: true },
    { id: "vendor_onboard", icon: Users, name: "Onboard Vendors", description: "Add new vendors to the platform", defaultEnabled: true },
    { id: "vendor_compliance", icon: Shield, name: "Vendor Compliance Review", description: "Review and approve vendor compliance documents", defaultEnabled: true },
    { id: "rate_cards", icon: DollarSign, name: "Rate Card Management", description: "Create, edit, and approve vendor rate cards", defaultEnabled: true },
    { id: "vendor_performance", icon: BarChart3, name: "Vendor Performance Analytics", description: "View scorecards and KPI reports", defaultEnabled: true },
    { id: "order_oversight", icon: Calendar, name: "Order Oversight", description: "View and manage all orders across sectors", defaultEnabled: false },
  ],
  operator: [
    { id: "enterprise_events", icon: Calendar, name: "Enterprise Event Management", description: "Create and manage events across your enterprise", defaultEnabled: true },
    { id: "sector_mgmt", icon: Building2, name: "Sector Management", description: "Configure and manage your sectors", defaultEnabled: true },
    { id: "staff_mgmt", icon: Users, name: "Workforce Management", description: "Assign and manage staff across enterprise", defaultEnabled: true },
    { id: "event_financials", icon: DollarSign, name: "Event Financials", description: "View costs and billing for all events", defaultEnabled: true },
    { id: "approve_events", icon: Shield, name: "Approve Events", description: "Approve event requests from sectors", defaultEnabled: false },
    { id: "enterprise_reports", icon: BarChart3, name: "Enterprise Reports", description: "Generate analytics for your enterprise", defaultEnabled: true },
  ],
  sector: [
    { id: "sector_events", icon: Calendar, name: "Sector Event Management", description: "Create and manage events at your location", defaultEnabled: true },
    { id: "location_staff", icon: Users, name: "Location Staff Management", description: "Schedule and manage staff at your sector", defaultEnabled: true },
    { id: "timesheet_approval", icon: FileText, name: "Timesheet Approval", description: "Review and approve staff timesheets", defaultEnabled: true },
    { id: "vendor_rates", icon: DollarSign, name: "View Vendor Rates", description: "Access rate cards for approved vendors", defaultEnabled: true },
    { id: "event_costs", icon: BarChart3, name: "Event Cost Visibility", description: "View billing for your events", defaultEnabled: false },
  ],
  client: [
    { id: "create_orders", icon: Calendar, name: "Create Orders", description: "Request staffing for events", defaultEnabled: true },
    { id: "view_orders", icon: FileText, name: "View My Orders", description: "Track your event orders", defaultEnabled: true },
    { id: "vendor_selection", icon: Package, name: "Vendor Selection", description: "View and request specific vendors", defaultEnabled: true },
    { id: "staff_review", icon: Users, name: "Staff Review", description: "Rate staff and request changes", defaultEnabled: true },
    { id: "invoices", icon: DollarSign, name: "Billing & Invoices", description: "View and download invoices", defaultEnabled: true },
    { id: "spend_analytics", icon: BarChart3, name: "Spend Analytics", description: "View your spending trends", defaultEnabled: false },
  ],
  vendor: [
    { id: "order_fulfillment", icon: Calendar, name: "Order Fulfillment", description: "Accept and manage assigned orders", defaultEnabled: true },
    { id: "my_workforce", icon: Users, name: "My Workforce", description: "Manage your staff members", defaultEnabled: true },
    { id: "staff_compliance", icon: Shield, name: "Staff Compliance", description: "Track certifications and background checks", defaultEnabled: true },
    { id: "my_rates", icon: DollarSign, name: "Rate Management", description: "View and propose rate cards", defaultEnabled: true },
    { id: "my_invoices", icon: FileText, name: "Invoices & Payments", description: "Create and track invoices", defaultEnabled: true },
    { id: "performance", icon: BarChart3, name: "Performance Dashboard", description: "View your scorecard and metrics", defaultEnabled: false },
  ],
  workforce: [
    { id: "my_schedule", icon: Calendar, name: "View My Schedule", description: "See upcoming shifts and assignments", defaultEnabled: true },
    { id: "clock_inout", icon: FileText, name: "Clock In/Out", description: "Record shift start and end times", defaultEnabled: true },
    { id: "my_profile", icon: Users, name: "My Profile", description: "Update contact info and availability", defaultEnabled: true },
    { id: "upload_certs", icon: Shield, name: "Upload Certifications", description: "Add certificates and licenses", defaultEnabled: true },
    { id: "earnings", icon: DollarSign, name: "View Earnings", description: "See pay, hours, and payment history", defaultEnabled: true },
    { id: "performance_stats", icon: BarChart3, name: "My Performance", description: "View ratings and reliability metrics", defaultEnabled: false },
  ]
};

export default function UserPermissionsModal({ user, open, onClose, onSave, isSaving }) {
  const [selectedRole, setSelectedRole] = useState(user?.user_role || "client");
  const [permissions, setPermissions] = useState({});

  // Initialize permissions when user or role changes
  useEffect(() => {
    if (user && open) {
      const rolePerms = ROLE_PERMISSIONS[user.user_role || "client"] || [];
      const initialPerms = {};
      rolePerms.forEach(perm => {
        initialPerms[perm.id] = perm.defaultEnabled;
      });
      setPermissions(initialPerms);
      setSelectedRole(user.user_role || "client");
    }
  }, [user, open]);

  // Update permissions when role changes
  useEffect(() => {
    const rolePerms = ROLE_PERMISSIONS[selectedRole] || [];
    const newPerms = {};
    rolePerms.forEach(perm => {
      newPerms[perm.id] = perm.defaultEnabled;
    });
    setPermissions(newPerms);
  }, [selectedRole]);

  const handleToggle = (permId) => {
    setPermissions(prev => ({
      ...prev,
      [permId]: !prev[permId]
    }));
  };

  const handleSave = () => {
    onSave({
      ...user,
      user_role: selectedRole,
      permissions: Object.keys(permissions).filter(key => permissions[key])
    });
    onClose();
  };

  if (!user) return null;

  const roleTemplate = ROLE_TEMPLATES[selectedRole];
  const rolePermissions = ROLE_PERMISSIONS[selectedRole] || [];
  const userInitial = user.full_name?.charAt(0).toUpperCase() || user.email?.charAt(0).toUpperCase() || "U";

  return (
    <Dialog open={open} onOpenChange={onClose}>
      <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <div className="flex items-center justify-between">
            <DialogTitle className="text-xl font-bold text-slate-900">User Permissions</DialogTitle>
          </div>
        </DialogHeader>

        {/* User Info */}
        <div className="flex items-center justify-between py-4 border-b border-slate-200">
          <div className="flex items-center gap-3">
            <Avatar className="w-14 h-14 border-2 border-slate-200">
              <AvatarImage src={user.profile_picture} alt={user.full_name} />
              <AvatarFallback className="bg-gradient-to-br from-[#0A39DF] to-[#1C323E] text-white font-bold text-lg">
                {userInitial}
              </AvatarFallback>
            </Avatar>
            <div>
              <h3 className="font-semibold text-lg text-slate-900">{user.full_name}</h3>
              <p className="text-sm text-slate-500">{user.email}</p>
            </div>
          </div>
          <Button variant="link" className="text-[#0A39DF] text-sm">
            View profile <ExternalLink className="w-3 h-3 ml-1" />
          </Button>
        </div>

        {/* Info Alert */}
        <Alert className="bg-blue-50 border-blue-200">
          <Info className="w-4 h-4 text-blue-600" />
          <AlertDescription className="text-blue-800 text-sm">
            Permission list will change when you select a different user group
          </AlertDescription>
        </Alert>

        {/* User Group Selector */}
        <div className="space-y-2">
          <label className="text-sm font-medium text-slate-700">User Group</label>
          <Select value={selectedRole} onValueChange={setSelectedRole}>
            <SelectTrigger className="border-slate-300">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {Object.entries(ROLE_TEMPLATES).map(([key, role]) => (
                <SelectItem key={key} value={key}>
                  <div className="flex items-center gap-2">
                    <Badge className={role.color + " text-xs"}>{role.name}</Badge>
                  </div>
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>

        {/* Permissions List */}
        <div className="space-y-3 py-4">
          {rolePermissions.map((perm) => {
            const Icon = perm.icon;
            return (
              <div
                key={perm.id}
                className="flex items-center justify-between p-4 bg-slate-50 rounded-lg hover:bg-slate-100 transition-colors"
              >
                <div className="flex items-center gap-4 flex-1">
                  <div className="w-10 h-10 bg-white rounded-lg flex items-center justify-center shadow-sm border border-slate-200">
                    <Icon className="w-5 h-5 text-[#0A39DF]" />
                  </div>
                  <div className="flex-1">
                    <h4 className="font-semibold text-sm text-slate-900">{perm.name}</h4>
                    <p className="text-xs text-slate-500 mt-0.5">{perm.description}</p>
                  </div>
                </div>
                <Switch
                  checked={permissions[perm.id] || false}
                  onCheckedChange={() => handleToggle(perm.id)}
                  className="data-[state=checked]:bg-emerald-500"
                />
              </div>
            );
          })}
        </div>

        {/* Save Button */}
        <div className="flex justify-end pt-4 border-t border-slate-200">
          <Button onClick={handleSave} className="bg-[#0A39DF] hover:bg-[#0A39DF]/90 px-6">
            Save changes
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  );
}
