import React, { useState } from "react";
import { base44 } from "@/api/base44Client";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Settings, X, RefreshCw, Shield, Users, Package, Building2, UserCheck, Briefcase, HardHat } from "lucide-react";
import { motion, AnimatePresence } from "framer-motion";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";

const roles = [
  { value: "admin", label: "Administrator", icon: Shield, color: "from-red-500 to-red-700" },
  { value: "procurement", label: "Procurement", icon: Package, color: "from-purple-500 to-purple-700" },
  { value: "operator", label: "Operator", icon: Users, color: "from-blue-500 to-blue-700" },
  { value: "sector", label: "Sector Manager", icon: Building2, color: "from-cyan-500 to-cyan-700" },
  { value: "client", label: "Client", icon: Briefcase, color: "from-green-500 to-green-700" },
  { value: "vendor", label: "Vendor", icon: Package, color: "from-amber-500 to-amber-700" },
  { value: "workforce", label: "Workforce", icon: HardHat, color: "from-slate-500 to-slate-700" },
];

export default function RoleSwitcher() {
  const [isOpen, setIsOpen] = useState(false);
  const [isMinimized, setIsMinimized] = useState(true);
  const queryClient = useQueryClient();

  const { data: user, refetch } = useQuery({
    queryKey: ['current-user'],
    queryFn: () => base44.auth.me(),
  });

  const currentRole = user?.user_role || user?.role || "admin";
  const currentRoleData = roles.find(r => r.value === currentRole);

  const handleRoleChange = async (newRole) => {
    try {
      // Update the user's role
      await base44.auth.updateMe({
        user_role: newRole,
      });

      // Invalidate all queries to refetch with new role
      queryClient.invalidateQueries();
      
      // Refetch user data
      await refetch();

      // Reload the page to apply new role completely
      window.location.reload();
    } catch (error) {
      console.error("Failed to switch role:", error);
    }
  };

  return (
    <>
      {/* Floating Toggle Button */}
      <AnimatePresence>
        {!isOpen && (
          <motion.div
            initial={{ scale: 0, opacity: 0 }}
            animate={{ scale: 1, opacity: 1 }}
            exit={{ scale: 0, opacity: 0 }}
            className="fixed bottom-24 right-6 z-40"
          >
            <Button
              onClick={() => setIsOpen(true)}
              className="w-14 h-14 rounded-full bg-gradient-to-br from-purple-500 to-purple-700 hover:from-purple-600 hover:to-purple-800 shadow-lg"
              title="Role Switcher (Dev Tool)"
            >
              <Settings className="w-6 h-6 text-white animate-spin-slow" />
            </Button>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Role Switcher Panel */}
      <AnimatePresence>
        {isOpen && (
          <motion.div
            initial={{ scale: 0, opacity: 0, x: 100 }}
            animate={{ scale: 1, opacity: 1, x: 0 }}
            exit={{ scale: 0, opacity: 0, x: 100 }}
            className="fixed bottom-24 right-6 z-40"
            style={{ width: isMinimized ? '300px' : '400px' }}
          >
            <Card className="shadow-2xl border-2 border-purple-300 overflow-hidden">
              {/* Header */}
              <CardHeader className="bg-gradient-to-br from-purple-500 to-purple-700 text-white p-4">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <Settings className="w-5 h-5" />
                    <CardTitle className="text-white text-base">Role Switcher</CardTitle>
                    <Badge className="bg-yellow-400 text-yellow-900 text-xs">DEV</Badge>
                  </div>
                  <div className="flex items-center gap-2">
                    <Button
                      variant="ghost"
                      size="icon"
                      onClick={() => setIsMinimized(!isMinimized)}
                      className="text-white hover:bg-white/20 h-8 w-8"
                    >
                      <RefreshCw className="w-4 h-4" />
                    </Button>
                    <Button
                      variant="ghost"
                      size="icon"
                      onClick={() => setIsOpen(false)}
                      className="text-white hover:bg-white/20 h-8 w-8"
                    >
                      <X className="w-4 h-4" />
                    </Button>
                  </div>
                </div>
              </CardHeader>

              <CardContent className="p-4 space-y-4">
                {/* Current Role Display */}
                <div className="p-4 bg-gradient-to-br from-slate-50 to-slate-100 rounded-lg border-2 border-slate-200">
                  <p className="text-xs text-slate-500 mb-2">Current Role</p>
                  <div className="flex items-center gap-3">
                    <div className={`w-10 h-10 bg-gradient-to-br ${currentRoleData?.color} rounded-lg flex items-center justify-center`}>
                      {currentRoleData?.icon && <currentRoleData.icon className="w-5 h-5 text-white" />}
                    </div>
                    <div>
                      <p className="font-bold text-[#1C323E]">{currentRoleData?.label}</p>
                      <p className="text-xs text-slate-500">{user?.email}</p>
                    </div>
                  </div>
                </div>

                {/* Role Selector */}
                <div>
                  <label className="text-sm font-semibold text-slate-700 mb-2 block">
                    Switch to Role
                  </label>
                  <Select value={currentRole} onValueChange={handleRoleChange}>
                    <SelectTrigger className="w-full">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      {roles.map((role) => (
                        <SelectItem key={role.value} value={role.value}>
                          <div className="flex items-center gap-2">
                            <role.icon className="w-4 h-4" />
                            <span>{role.label}</span>
                          </div>
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>

                {/* Quick Role Grid */}
                {!isMinimized && (
                  <div>
                    <p className="text-sm font-semibold text-slate-700 mb-3">Quick Switch</p>
                    <div className="grid grid-cols-2 gap-2">
                      {roles.map((role) => (
                        <Button
                          key={role.value}
                          variant={currentRole === role.value ? "default" : "outline"}
                          size="sm"
                          onClick={() => handleRoleChange(role.value)}
                          className={currentRole === role.value ? `bg-gradient-to-br ${role.color} text-white` : ""}
                        >
                          <role.icon className="w-4 h-4 mr-2" />
                          {role.label}
                        </Button>
                      ))}
                    </div>
                  </div>
                )}

                {/* Warning */}
                <div className="p-3 bg-yellow-50 border border-yellow-200 rounded-lg">
                  <p className="text-xs text-yellow-800">
                    <strong>⚠️ Development Tool:</strong> This switcher is for testing only. 
                    Changes will persist until you switch again or log out.
                  </p>
                </div>

                {/* Info Box */}
                {!isMinimized && (
                  <div className="space-y-2 text-xs text-slate-600">
                    <div className="flex items-start gap-2">
                      <div className="w-1 h-1 bg-slate-400 rounded-full mt-1.5" />
                      <p><strong>Admin:</strong> Full access to all features</p>
                    </div>
                    <div className="flex items-start gap-2">
                      <div className="w-1 h-1 bg-slate-400 rounded-full mt-1.5" />
                      <p><strong>Procurement:</strong> Vendor management & orders</p>
                    </div>
                    <div className="flex items-start gap-2">
                      <div className="w-1 h-1 bg-slate-400 rounded-full mt-1.5" />
                      <p><strong>Operator/Sector:</strong> Event & staff management</p>
                    </div>
                    <div className="flex items-start gap-2">
                      <div className="w-1 h-1 bg-slate-400 rounded-full mt-1.5" />
                      <p><strong>Client:</strong> Create orders, view invoices</p>
                    </div>
                    <div className="flex items-start gap-2">
                      <div className="w-1 h-1 bg-slate-400 rounded-full mt-1.5" />
                      <p><strong>Vendor:</strong> Manage own staff & orders</p>
                    </div>
                    <div className="flex items-start gap-2">
                      <div className="w-1 h-1 bg-slate-400 rounded-full mt-1.5" />
                      <p><strong>Workforce:</strong> View shifts & earnings</p>
                    </div>
                  </div>
                )}
              </CardContent>
            </Card>
          </motion.div>
        )}
      </AnimatePresence>
    </>
  );
}