"use client";

import { useState, useEffect, useMemo } from "react";
import useSWR from "swr";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  Button,
  Input,
  Label,
  Checkbox,
  Badge,
  Avatar,
  AvatarFallback,
  AvatarImage,
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
  Switch,
} from "../../ui";
import { toast } from "sonner";
import { cn } from "../../utils";
import {
  X,
  Search,
  Eye,
  EyeOff,
  Loader2,
  Ban,
  UserCog,
  Store,
  CheckCircle2,
  User,
  Briefcase,
  ShieldCheck,
  KeyRound,
} from "lucide-react";

interface UnifiedProfileDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  data?: any;
  mode?: "create" | "edit" | "view";
  viewMode: "admin" | "crm" | "srm";
  roles?: any[];
  onSaveProfile?: (data: any, id?: string) => Promise<void>;
  onSaveRoles?: (userId: string, roleCodes: string[]) => Promise<void>;
  onSavePassword?: (userId: string, password: string) => Promise<void>;
}

const fetcher = async (url: string) => {
  const res = await fetch(url);
  if (!res.ok) throw new Error("Failed to fetch");
  const data = await res.json();
  return Array.isArray(data) ? data : data.items || data.data || [];
};

export function UnifiedProfileDialog({
  open,
  onOpenChange,
  data,
  mode = "edit",
  viewMode = "admin",
  roles = [],
  onSaveProfile,
  onSaveRoles,
  onSavePassword,
}: UnifiedProfileDialogProps) {
  // -- Data Fetching --
  const { data: departments } = useSWR<{ id: string; name: string }[]>(
    "/api/departments?status=active",
    fetcher,
  );
  const { data: jobTitles } = useSWR<{ id: string; name: string }[]>(
    "/api/job-titles?status=active",
    fetcher,
  );
  const { data: suppliers } = useSWR<{ id: string; name: string }[]>(
    "/api/suppliers?pageSize=100",
    fetcher,
  );
  const { data: customerGroups } = useSWR<{ id: string; name: string }[]>(
    "/api/crud/customer-groups?status=active",
    fetcher,
  );
  const { data: branches } = useSWR<{ id: string; name: string }[]>(
    "/api/branches",
    fetcher,
  );

  // -- State --
  const [activeSection, setActiveSection] = useState("general");
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState("");

  // Form State
  const [userType, setUserType] = useState<string>("employee");
  const [profileData, setProfileData] = useState<any>({});
  const [selectedRoles, setSelectedRoles] = useState<string[]>([]);
  const [selectedBranches, setSelectedBranches] = useState<string[]>([]);
  const [passwordData, setPasswordData] = useState({
    password: "",
    confirm: "",
  });
  const [showPassword, setShowPassword] = useState(false);
  const [roleSearchQuery, setRoleSearchQuery] = useState("");
  const [enableAccount, setEnableAccount] = useState(false);

  const displayData = data || {};

  // Derived state
  const isCustomer = viewMode === "crm" || userType === "customer";

  // -- Navigation Items (Conditional) --
  const navItems = useMemo(() => {
    // For Customers: Only ONE section with all info merged
    if (isCustomer) {
      return [{ id: "general", label: "Thông tin khách hàng", icon: User }];
    }

    // For Employees/Suppliers: Multiple sections
    const items: { id: string; label: string; icon: any }[] = [
      { id: "general", label: "Thông tin chung", icon: User },
    ];

    if (userType === "employee") {
      items.push({ id: "work", label: "Công việc", icon: Briefcase });
    }

    if (userType === "supplier") {
      items.push({ id: "supplier_link", label: "Nhà cung cấp", icon: Store });
    }

    // Roles & Security for users with accounts
    items.push({ id: "roles", label: "Phân quyền", icon: ShieldCheck });
    items.push({ id: "security", label: "Bảo mật", icon: KeyRound });

    return items;
  }, [userType, isCustomer]);

  // -- Initialization --
  useEffect(() => {
    if (open) {
      setError("");
      setIsSubmitting(false);
      setActiveSection("general");

      if (mode === "create") {
        const initialType =
          viewMode === "crm"
            ? "customer"
            : viewMode === "srm"
              ? "supplier"
              : "employee";
        setUserType(initialType);
        setProfileData({
          status: "active",
          name: "",
          email: "",
          phone: "",
          address: "",
          departmentId: "",
          jobTitleId: "",
          supplierId: "",
          groupId: "",
          idNumber: "",
          gender: "",
          birthday: "",
        });
        setSelectedRoles([]);
        setSelectedBranches([]);
        setPasswordData({ password: "", confirm: "" });
        setEnableAccount(false);
      } else {
        const d = displayData;
        let type = "employee";
        if (viewMode === "crm" || d.userType === "customer" || d.customerId)
          type = "customer";
        else if (d.userType === "supplier" || d.supplierId) type = "supplier";
        else if (d.userType) type = d.userType;

        setUserType(type);
        setProfileData({
          status: d.status || "active",
          name: d.name || "",
          email: d.email || "",
          phone: d.phone || d.profiles?.phone || "",
          address: d.address || d.profiles?.address || "",
          departmentId: d.departmentId || d.profiles?.departmentId || "",
          jobTitleId: d.jobTitleId || d.profiles?.jobTitleId || "",
          supplierId: d.supplierId || d.profiles?.supplierId || "",
          groupId: d.groupId || "",
          idNumber: d.idNumber || "",
          gender: d.gender || "",
          birthday: d.birthday
            ? new Date(d.birthday).toISOString().split("T")[0]
            : "",
        });
        const roles = d.roleCodes || [];
        setSelectedRoles(roles);
        setSelectedBranches(d.branchIds || []);
        setPasswordData({ password: "", confirm: "" });
        // Enable account if user has roles or if it's not a customer (employees always have accounts?)
        // For now, if roles exist, we assume account is enabled.
        setEnableAccount(roles.length > 0 || type !== "customer");
      }
    }
  }, [open, data, mode, viewMode]);

  useEffect(() => {
    if (open && branches?.length === 1) {
      if (mode === "create" || (data?.branchIds?.length || 0) === 0) {
        if (selectedBranches.length === 0) {
          setSelectedBranches([branches[0].id]);
        }
      }
    }
  }, [open, branches, mode, data]);

  // -- Helpers --
  const getInitials = (name: string | null) => {
    if (!name) return "U";
    return name
      .split(" ")
      .map((n) => n[0])
      .join("")
      .toUpperCase()
      .slice(0, 2);
  };

  const filteredRoles = useMemo(() => {
    if (!roleSearchQuery.trim()) return roles;
    const query = roleSearchQuery.toLowerCase();
    return roles.filter(
      (r) =>
        r.name.toLowerCase().includes(query) ||
        r.code.toLowerCase().includes(query),
    );
  }, [roles, roleSearchQuery]);

  // -- Save Handler --
  const handleSave = async () => {
    try {
      setIsSubmitting(true);
      setError("");

      // Prepare payload
      const payload: any = {
        ...profileData,
        userType, // Add userType to payload
        roleCodes: selectedRoles,
        branchIds: selectedBranches,
      };

      // Handle Password for Customer
      if (isCustomer) {
        if (enableAccount) {
          if (passwordData.password) {
            if (passwordData.password !== passwordData.confirm) {
              setError("Mật khẩu xác nhận không khớp");
              setIsSubmitting(false);
              return;
            }
            if (passwordData.password.length < 6) {
              setError("Mật khẩu phải có ít nhất 6 ký tự");
              setIsSubmitting(false);
              return;
            }
            payload.password = passwordData.password;
          } else if (mode === "create") {
            // If creating a customer account, password is required
            setError("Mật khẩu là bắt buộc cho tài khoản khách hàng mới");
            setIsSubmitting(false);
            return;
          }
        } else {
          // If account not enabled, default or clear
          if (mode === "create") {
            payload.password = "Goeat@123456";
          } else {
            delete payload.password;
            payload.roleCodes = [];
          }
        }
      } else {
        if (passwordData.password) {
          if (passwordData.password !== passwordData.confirm) {
            setError("Mật khẩu xác nhận không khớp");
            setIsSubmitting(false);
            return;
          }
          if (passwordData.password.length < 6) {
            setError("Mật khẩu phải có ít nhất 6 ký tự");
            setIsSubmitting(false);
            return;
          }
          payload.password = passwordData.password;
        } else if (mode === "create") {
          setError("Mật khẩu là bắt buộc cho tài khoản mới");
          setIsSubmitting(false);
          return;
        }
      }

      if (!payload.name) {
        setError("Tên là bắt buộc");
        setIsSubmitting(false);
        return;
      }

      // Call API
      if (mode === "create") {
        if (onSaveProfile) await onSaveProfile(payload);
        toast.success("Đã tạo hồ sơ mới thành công");
      } else {
        // Save all data at once (profile + roles + branches)
        if (onSaveProfile) {
          await onSaveProfile(payload, data.id);
        }

        // Also save password if provided
        if (payload.password && onSavePassword) {
          await onSavePassword(data.id, payload.password);
        }

        toast.success("Đã lưu thông tin");
      }

      onOpenChange(false);
    } catch (e: any) {
      console.error(e);
      setError(e.message || "Đã xảy ra lỗi");
      toast.error("Đã xảy ra lỗi khi lưu thông tin");
    } finally {
      setIsSubmitting(false);
    }
  };

  // -- Render Helpers --
  const isActive = profileData.status === "active";

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="w-[100dvw] h-[100dvh] max-w-none max-h-none sm:w-auto sm:max-w-5xl sm:h-[85vh] flex flex-col p-0 gap-0 overflow-hidden border border-[#dee3e9] dark:border-[#1c1e21] shadow-[0_12px_32px_rgba(0,0,0,0.1)] bg-[#ffffff] dark:bg-[#0a1317] rounded-none sm:rounded-[12px] [&>button.absolute]:hidden">
        <DialogHeader className="sr-only">
          <DialogTitle>
            {mode === "create" ? "Tạo mới" : "Chỉnh sửa"}
          </DialogTitle>
        </DialogHeader>

        <div className="flex flex-col w-full h-full overflow-hidden">
          {/* TOP HEADER: Profile Info + Actions */}
          <div className="shrink-0 flex flex-col border-b border-[#e2e8f0] dark:border-[#334155] bg-[#f8fafc] dark:bg-[#0f172a] px-6 pt-5 pb-0">
            <div className="flex flex-col sm:flex-row sm:items-start justify-between gap-4 pb-5">
              {/* Profile Header */}
              <div className="flex items-center gap-4">
                <div className="relative">
                  <Avatar className="h-12 w-12 sm:h-14 sm:w-14 rounded-full border border-[#e2e8f0] dark:border-[#334155]">
                    <AvatarImage
                      src={displayData.avatar}
                      className="object-cover rounded-full"
                    />
                    <AvatarFallback className="text-[16px] sm:text-[18px] font-semibold bg-[#1641CE] text-white dark:bg-[#1E40AF] dark:text-white rounded-full">
                      {getInitials(profileData.name)}
                    </AvatarFallback>
                  </Avatar>
                  <div
                    className={cn(
                      "absolute -bottom-0.5 -right-0.5 w-3.5 h-3.5 sm:w-4 sm:h-4 border-[2px] border-[#f8fafc] dark:border-[#0f172a] rounded-full z-10",
                      isActive ? "bg-[#10b981]" : "bg-[#cbd5e1]"
                    )}
                    title={isActive ? "Hoạt động" : "Đã khóa"}
                  />
                </div>
                <div>
                  <h2 className="text-[18px] sm:text-[20px] font-semibold leading-tight text-[#0f172a] dark:text-white">
                    {profileData.name || "Chưa đặt tên"}
                  </h2>
                  <p className="mt-1 text-[13px] text-[#64748b] dark:text-[#94a3b8]">
                    {profileData.email || profileData.phone || "Chưa có thông tin liên hệ"}
                  </p>
                </div>
              </div>

              {/* Actions & User Type */}
              <div className="flex items-center gap-2 sm:gap-3 shrink-0">
                {viewMode === "admin" ? (
                  <Select
                    value={userType}
                    onValueChange={(val) => setUserType(val)}
                    disabled={mode === "view"}
                  >
                    <SelectTrigger className="w-[140px] bg-white dark:bg-[#1e293b] border-[#e2e8f0] dark:border-[#334155] focus:ring-[#1641CE] focus:border-[#1641CE] h-9 rounded-md">
                      <SelectValue placeholder="Chọn loại" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="employee">
                        <span className="flex items-center gap-2">
                          <UserCog className="h-4 w-4 text-[#1641CE]" />
                          Nhân viên
                        </span>
                      </SelectItem>
                      <SelectItem value="customer">
                        <span className="flex items-center gap-2">
                          <User className="h-4 w-4 text-[#059669]" />
                          Khách hàng
                        </span>
                      </SelectItem>
                      <SelectItem value="supplier">
                        <span className="flex items-center gap-2">
                          <Store className="h-4 w-4 text-[#EA580C]" />
                          Nhà cung cấp
                        </span>
                      </SelectItem>
                    </SelectContent>
                  </Select>
                ) : (
                  <div className="flex items-center gap-1.5 shrink-0">
                    {userType === "employee" && (
                      <span className="text-[12px] px-2.5 py-1 font-semibold rounded-md bg-[#1641CE]/10 text-[#1641CE] border border-[#1641CE]/20 inline-flex items-center">
                        <UserCog className="h-3.5 w-3.5 mr-1.5" /> Nhân viên
                      </span>
                    )}
                    {userType === "customer" && (
                      <span className="text-[12px] px-2.5 py-1 font-semibold rounded-md bg-[#059669] text-white inline-flex items-center">
                        <User className="h-3.5 w-3.5 mr-1.5" /> Khách hàng
                      </span>
                    )}
                    {userType === "supplier" && (
                      <span className="text-[12px] px-2.5 py-1 font-semibold rounded-md bg-[#EA580C] text-white inline-flex items-center">
                        <Store className="h-3.5 w-3.5 mr-1.5" /> Nhà cung cấp
                      </span>
                    )}
                  </div>
                )}
                
                <Button
                  variant="outline"
                  onClick={() => onOpenChange(false)}
                  className="border border-[#e2e8f0] bg-white dark:border-[#334155] text-[#475569] dark:text-white dark:bg-[#1e293b] hover:bg-[#f1f5f9] gap-2 h-9 rounded-md px-4 text-[13px] font-medium"
                >
                  <span className="hidden sm:inline">Đóng</span>
                  <X className="h-4 w-4 sm:hidden" />
                </Button>
                <Button
                  onClick={handleSave}
                  disabled={isSubmitting}
                  className="bg-primary hover:bg-primary/90 text-primary-foreground min-w-[80px] h-9 px-5 gap-2 font-medium text-[13px] rounded-md"
                >
                  {isSubmitting ? (
                    <Loader2 className="h-4 w-4 animate-spin" />
                  ) : (
                    <CheckCircle2 className="h-4 w-4" />
                  )}
                  <span>{mode === "create" ? "Tạo" : "Lưu"}</span>
                </Button>
              </div>
            </div>

            {/* Corporate Navy Underline Tabs */}
            <nav className="flex gap-6 overflow-x-auto hide-scrollbar">
              {navItems.map((item) => (
                <button
                  key={item.id}
                  onClick={() => setActiveSection(item.id)}
                  className={cn(
                    "relative pb-3 text-[14px] font-medium transition-all whitespace-nowrap flex items-center gap-2",
                    activeSection === item.id
                      ? "text-primary dark:text-primary"
                      : "text-[#64748b] hover:text-[#0f172a] dark:text-[#94a3b8] dark:hover:text-white"
                  )}
                >
                  <item.icon
                    className={cn(
                      "h-[16px] w-[16px]",
                      activeSection === item.id
                        ? "text-primary dark:text-primary"
                        : "text-[#94a3b8]"
                    )}
                    strokeWidth={2}
                  />
                  {item.label}
                  {activeSection === item.id && (
                    <div className="absolute bottom-0 left-0 right-0 h-[2px] bg-primary dark:bg-primary rounded-t-sm" />
                  )}
                </button>
              ))}
            </nav>
          </div>

          {/* MAIN CONTENT AREA */}
          <div className="flex-1 bg-white dark:bg-[#0f172a] overflow-y-auto overscroll-contain touch-pan-y" style={{ WebkitOverflowScrolling: 'touch' }}>
              <div className="p-4 sm:p-5 max-w-4xl mx-auto space-y-4 pb-20">
                {/* General Section */}
                {activeSection === "general" && (
                  <div className="space-y-4 animate-in fade-in zoom-in-95 duration-200">

                    <div className="grid md:grid-cols-2 gap-x-6 gap-y-4">
                      <div className="space-y-1.5">
                        <Label className="text-[13px] font-medium text-[#334155] dark:text-[#cbd5e1]">
                          Họ và tên <span className="text-[#e41e3f]">*</span>
                        </Label>
                        <Input
                          value={profileData.name}
                          onChange={(e) =>
                            setProfileData({
                              ...profileData,
                              name: e.target.value,
                            })
                          }
                          placeholder="Nguyễn Văn A"
                          className="bg-white dark:bg-[#1e293b] border-[#e2e8f0] dark:border-[#334155] focus:ring-primary focus:border-primary rounded-md h-9 text-[13px]"
                        />
                      </div>
                      <div className="space-y-1.5">
                        <Label className="text-[13px] font-medium text-[#334155] dark:text-[#cbd5e1]">Email</Label>
                        <Input
                          value={profileData.email}
                          onChange={(e) =>
                            setProfileData({
                              ...profileData,
                              email: e.target.value,
                            })
                          }
                          placeholder="email@example.com"
                          className="bg-white dark:bg-[#1e293b] border-[#e2e8f0] dark:border-[#334155] focus:ring-primary focus:border-primary rounded-md h-9 text-[13px]"
                        />
                      </div>
                      <div className="space-y-1.5">
                        <Label className="text-[13px] font-medium text-[#334155] dark:text-[#cbd5e1]">Số điện thoại</Label>
                        <Input
                          value={profileData.phone}
                          onChange={(e) =>
                            setProfileData({
                              ...profileData,
                              phone: e.target.value,
                            })
                          }
                          placeholder="0912..."
                          className="bg-white dark:bg-[#1e293b] border-[#e2e8f0] dark:border-[#334155] focus:ring-primary focus:border-primary rounded-md h-9 text-[13px]"
                        />
                      </div>
                      <div className="space-y-1.5">
                        <Label className="text-[13px] font-medium text-[#334155] dark:text-[#cbd5e1]">Địa chỉ</Label>
                        <Input
                          value={profileData.address}
                          onChange={(e) =>
                            setProfileData({
                              ...profileData,
                              address: e.target.value,
                            })
                          }
                          placeholder="Số nhà, đường..."
                          className="bg-white dark:bg-[#1e293b] border-[#e2e8f0] dark:border-[#334155] focus:ring-primary focus:border-primary rounded-md h-9 text-[13px]"
                        />
                      </div>
                      {/* Status Toggle */}
                      {viewMode === "admin" && (
                        <div className="space-y-1.5">
                          <Label className="text-[13px] font-medium text-[#334155] dark:text-[#cbd5e1]">Trạng thái</Label>
                          <div className="flex items-center gap-3 h-9 px-3 rounded-[6px] border border-[#ced0d4] dark:border-[#333840] bg-[#ffffff] dark:bg-[#0a1317]">
                            <Switch
                              id="user-active-switch"
                              checked={isActive}
                              onCheckedChange={(checked) =>
                                setProfileData({
                                  ...profileData,
                                  status: checked ? "active" : "inactive",
                                })
                              }
                            />
                            <span
                              className={cn(
                                "text-[13px] font-bold tracking-[-0.13px]",
                                isActive ? "text-[#31a24c]" : "text-[#444950]",
                              )}
                            >
                              {isActive ? "Hoạt động" : "Đã khóa"}
                            </span>
                          </div>
                        </div>
                      )}
                      {/* Additional Info for All */}
                      <div className="space-y-1.5">
                        <Label className="text-[13px] font-medium text-[#334155] dark:text-[#cbd5e1]">Ngày sinh</Label>
                        <Input
                          type="date"
                          value={profileData.birthday}
                          onChange={(e) =>
                            setProfileData({
                              ...profileData,
                              birthday: e.target.value,
                            })
                          }
                          className="bg-white dark:bg-[#1e293b] border-[#e2e8f0] dark:border-[#334155] focus:ring-primary focus:border-primary rounded-md h-9 text-[13px]"
                        />
                      </div>
                      <div className="space-y-1.5">
                        <Label className="text-[13px] font-medium text-[#334155] dark:text-[#cbd5e1]">Giới tính</Label>
                        <Select
                          value={profileData.gender}
                          onValueChange={(val) =>
                            setProfileData({ ...profileData, gender: val })
                          }
                        >
                          <SelectTrigger className="bg-white dark:bg-[#1e293b] border-[#e2e8f0] dark:border-[#334155] focus:ring-primary focus:border-primary rounded-md h-9 text-[13px]">
                            <SelectValue placeholder="Chọn giới tính" />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="male">Nam</SelectItem>
                            <SelectItem value="female">Nữ</SelectItem>
                            <SelectItem value="other">Khác</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>
                      <div className="space-y-1.5">
                        <Label className="text-[13px] font-medium text-[#334155] dark:text-[#cbd5e1]">CCCD/CMND</Label>
                        <Input
                          value={profileData.idNumber}
                          onChange={(e) =>
                            setProfileData({
                              ...profileData,
                              idNumber: e.target.value,
                            })
                          }
                          className="bg-white dark:bg-[#1e293b] border-[#e2e8f0] dark:border-[#334155] focus:ring-primary focus:border-primary rounded-md h-9 text-[13px]"
                        />
                      </div>

                      {/* Customer Specific */}
                      {isCustomer && (
                        <div className="space-y-1.5">
                          <Label className="text-[13px] font-medium text-[#334155] dark:text-[#cbd5e1]">
                            Nhóm khách hàng
                          </Label>
                          <Select
                            value={profileData.groupId}
                            onValueChange={(val) =>
                              setProfileData({ ...profileData, groupId: val })
                            }
                          >
                            <SelectTrigger className="bg-white dark:bg-[#1e293b] border-[#e2e8f0] dark:border-[#334155] focus:ring-primary focus:border-primary rounded-md h-9 text-[13px]">
                              <SelectValue placeholder="Chọn nhóm" />
                            </SelectTrigger>
                            <SelectContent>
                              {customerGroups?.map((g) => (
                                <SelectItem key={g.id} value={g.id}>
                                  {g.name}
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                        </div>
                      )}
                    </div>

                    {isCustomer && (
                      <div className="pt-4">
                        <div className="flex items-center justify-between mb-4 border-b border-[#dee3e9] pb-2">
                          <h3 className="text-[18px] font-bold tracking-[-0.14px] text-[#0a1317] dark:text-white">
                            Tài khoản đăng nhập
                          </h3>
                          <Switch
                            checked={enableAccount}
                            onCheckedChange={setEnableAccount}
                          />
                        </div>

                        {enableAccount && (
                          <div className="space-y-4 animate-in fade-in slide-in-from-top-2">
                            <div className="grid md:grid-cols-2 gap-x-6 gap-y-4">
                              <div className="space-y-1.5 col-span-2 md:col-span-1">
                                <Label className="text-[13px] font-medium text-[#334155] dark:text-[#cbd5e1]">
                                  Mật khẩu
                                </Label>
                                <div className="relative">
                                  <Input
                                    type={showPassword ? "text" : "password"}
                                    value={passwordData.password}
                                    onChange={(e) =>
                                      setPasswordData((prev) => ({
                                        ...prev,
                                        password: e.target.value,
                                      }))
                                    }
                                    placeholder="Nhập mật khẩu"
                                    className="pr-10 bg-[#ffffff] dark:bg-[#0a1317] border-[#ced0d4] dark:border-[#333840] focus:ring-[#0064e0] focus:border-[#0064e0] rounded-[6px] h-9 text-[14px]"
                                  />
                                  <Button
                                    type="button"
                                    variant="ghost"
                                    size="icon"
                                    className="absolute right-0 top-0 h-full w-9 text-[#444950] hover:text-[#0a1317]"
                                    onClick={() =>
                                      setShowPassword(!showPassword)
                                    }
                                  >
                                    {showPassword ? (
                                      <EyeOff className="h-4 w-4" />
                                    ) : (
                                      <Eye className="h-4 w-4" />
                                    )}
                                  </Button>
                                </div>
                                <p className="text-[12px] text-[#444950] mt-1.5 flex items-center gap-1.5">
                                  <span className="inline-block w-1.5 h-1.5 rounded-full bg-[#0064e0]" />
                                  Mặc định:{" "}
                                  <span className="font-mono font-bold text-[#1c1e21] dark:text-white">
                                    Goeat@123456
                                  </span>
                                </p>
                              </div>
                            </div>

                            <div className="space-y-2 pt-2">
                              <Label className="text-[13px] font-medium text-[#334155] dark:text-[#cbd5e1]">
                                Phân quyền
                              </Label>
                              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                                {filteredRoles.map((role) => {
                                  const isSelected = selectedRoles.includes(
                                    role.code,
                                  );
                                  return (
                                    <div
                                      key={role.code}
                                      className={cn(
                                        "flex items-start gap-3 p-3 rounded-md border cursor-pointer hover:bg-slate-50 transition-colors",
                                        isSelected
                                          ? "border-blue-500 bg-blue-50/50"
                                          : "bg-background border-slate-200 dark:border-slate-800",
                                      )}
                                      onClick={() => {
                                        setSelectedRoles((prev) =>
                                          prev.includes(role.code)
                                            ? prev.filter(
                                              (c) => c !== role.code,
                                            )
                                            : [...prev, role.code],
                                        );
                                      }}
                                    >
                                      <Checkbox
                                        checked={isSelected}
                                        className="mt-1 data-[state=checked]:bg-blue-600 data-[state=checked]:border-blue-600"
                                      />
                                      <div className="space-y-0.5">
                                        <p className="text-sm font-medium text-slate-900 dark:text-slate-100">
                                          {role.name}
                                        </p>
                                        <p className="text-xs text-muted-foreground line-clamp-1">
                                          {role.description || role.code}
                                        </p>
                                      </div>
                                    </div>
                                  );
                                })}
                              </div>
                            </div>
                          </div>
                        )}
                      </div>
                    )}
                  </div>
                )}

                {/* Work Section */}
                {activeSection === "work" && (
                  <div className="space-y-4 animate-in fade-in zoom-in-95 duration-200">
                    <div className="grid md:grid-cols-2 gap-x-8 gap-y-6">
                      <div className="space-y-2">
                        <Label className="text-[13px] font-medium text-[#41454d] dark:text-[#9297a0]">Phòng ban</Label>
                        <Select
                          value={profileData.departmentId}
                          onValueChange={(val) =>
                            setProfileData({
                              ...profileData,
                              departmentId: val,
                            })
                          }
                        >
                          <SelectTrigger className="bg-[#ffffff] dark:bg-[#181d26] border-[#dddddd] dark:border-[#333840] focus:ring-[#458fff] focus:border-[#458fff] shadow-sm rounded-[6px]">
                            <SelectValue placeholder="Chọn phòng ban" />
                          </SelectTrigger>
                          <SelectContent>
                            {departments?.map((d) => (
                              <SelectItem key={d.id} value={d.id}>
                                {d.name}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>
                      <div className="space-y-2">
                        <Label className="text-[13px] font-medium text-[#41454d] dark:text-[#9297a0]">Chức danh</Label>
                        <Select
                          value={profileData.jobTitleId}
                          onValueChange={(val) =>
                            setProfileData({ ...profileData, jobTitleId: val })
                          }
                        >
                          <SelectTrigger className="bg-[#ffffff] dark:bg-[#181d26] border-[#dddddd] dark:border-[#333840] focus:ring-[#458fff] focus:border-[#458fff] shadow-sm rounded-[6px]">
                            <SelectValue placeholder="Chọn chức danh" />
                          </SelectTrigger>
                          <SelectContent>
                            {jobTitles?.map((j) => (
                              <SelectItem key={j.id} value={j.id}>
                                {j.name}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>
                      <div className="col-span-2 space-y-3 pt-2">
                        <Label className="text-[13px] font-medium text-[#41454d] dark:text-[#9297a0]">Chi nhánh làm việc</Label>
                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                          {branches?.map((branch) => {
                            const isSelected = selectedBranches.includes(branch.id);
                            return (
                              <div
                                key={branch.id}
                                className={cn(
                                  "flex items-center gap-3 p-3 rounded-md border cursor-pointer hover:bg-slate-50 transition-colors",
                                  isSelected
                                    ? "border-blue-500 bg-blue-50/50"
                                    : "bg-background border-slate-200 dark:border-slate-800",
                                )}
                                onClick={() => {
                                  setSelectedBranches((prev) =>
                                    prev.includes(branch.id)
                                      ? prev.filter((id) => id !== branch.id)
                                      : [...prev, branch.id],
                                  );
                                }}
                              >
                                <Checkbox
                                  checked={isSelected}
                                  className="data-[state=checked]:bg-blue-600 data-[state=checked]:border-blue-600"
                                />
                                <span className="text-sm font-medium text-slate-900 dark:text-slate-100">
                                  {branch.name}
                                </span>
                              </div>
                            );
                          })}
                        </div>
                      </div>
                    </div>
                  </div>
                )}

                {activeSection === "supplier_link" && (
                  <div className="space-y-4 animate-in fade-in zoom-in-95 duration-200">
                    <div className="max-w-2xl space-y-6">
                      <div className="space-y-2">
                        <Label className="text-[13px] font-medium text-[#41454d] dark:text-[#9297a0]">
                          Chọn nhà cung cấp
                        </Label>
                        <Select
                          value={profileData.supplierId}
                          onValueChange={(val) =>
                            setProfileData({ ...profileData, supplierId: val })
                          }
                        >
                          <SelectTrigger className="bg-[#ffffff] dark:bg-[#181d26] border-[#dddddd] dark:border-[#333840] focus:ring-[#458fff] focus:border-[#458fff] shadow-sm rounded-[6px]">
                            <SelectValue placeholder="Chọn nhà cung cấp" />
                          </SelectTrigger>
                          <SelectContent>
                            {suppliers?.map((s) => (
                              <SelectItem key={s.id} value={s.id}>
                                {s.name}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>
                      <div className="rounded-md bg-blue-50 p-4 text-sm text-blue-700 flex items-start gap-3">
                        <Store className="h-5 w-5 mt-0.5 shrink-0" />
                        <p>
                          Tài khoản này sẽ được liên kết với nhà cung cấp đã
                          chọn. Người dùng sẽ có quyền truy cập vào dữ liệu và
                          chức năng dành riêng cho nhà cung cấp này.
                        </p>
                      </div>
                    </div>
                  </div>
                )}

                {activeSection === "roles" && (
                  <div className="animate-in fade-in zoom-in-95 duration-200">
                    <div className="sticky -top-4 sm:-top-5 pt-2 sm:pt-2 pb-4 -mx-4 sm:-mx-5 px-4 sm:px-5 bg-white/95 dark:bg-[#0f172a]/95 backdrop-blur-sm z-10 border-b border-[#e2e8f0] dark:border-[#334155] mb-4 shadow-sm">
                      <div className="relative max-w-md">
                        <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-[#64748b]" />
                        <Input
                          placeholder="Tìm kiếm vai trò..."
                          value={roleSearchQuery}
                          onChange={(e) => setRoleSearchQuery(e.target.value)}
                          className="pl-9 bg-white dark:bg-[#1e293b] border-[#e2e8f0] dark:border-[#334155] focus:ring-primary focus:border-primary shadow-sm rounded-md h-9 text-[13px]"
                        />
                      </div>
                    </div>

                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                      {filteredRoles.map((role) => {
                        const isSelected = selectedRoles.includes(role.code);
                        return (
                          <div
                            key={role.code}
                            className={cn(
                              "flex items-start gap-3 p-3 rounded-md border cursor-pointer hover:bg-slate-50 transition-colors",
                              isSelected
                                ? "border-blue-500 bg-blue-50/50"
                                : "bg-background border-slate-200 dark:border-slate-800",
                            )}
                            onClick={() => {
                              setSelectedRoles((prev) =>
                                prev.includes(role.code)
                                  ? prev.filter((c) => c !== role.code)
                                  : [...prev, role.code],
                              );
                            }}
                          >
                            <Checkbox
                              checked={isSelected}
                              className="mt-1 data-[state=checked]:bg-blue-600 data-[state=checked]:border-blue-600"
                            />
                            <div className="space-y-0.5">
                              <p className="text-sm font-medium text-slate-900 dark:text-slate-100">
                                {role.name}
                              </p>
                              <p className="text-xs text-muted-foreground line-clamp-1">
                                {role.description || role.code}
                              </p>
                            </div>
                          </div>
                        );
                      })}
                    </div>
                  </div>
                )}

                {activeSection === "security" && (
                  <div className="space-y-4 animate-in fade-in zoom-in-95 duration-200">
                    <div className="max-w-xl space-y-6">
                      <div className="flex items-center gap-3 rounded-md bg-amber-50 p-4 text-sm text-amber-900 border border-amber-100">
                        <ShieldCheck className="h-5 w-5 shrink-0 text-amber-600" />
                        <span>
                          Mật khẩu mạnh giúp bảo vệ tài khoản khỏi truy cập trái
                          phép. Sử dụng ít nhất 6 ký tự bao gồm chữ và số.
                        </span>
                      </div>
                      <div className="grid md:grid-cols-2 gap-x-8 gap-y-6">
                        <div className="space-y-2">
                          <Label className="text-[13px] font-medium text-[#41454d] dark:text-[#9297a0]">Mật khẩu mới</Label>
                          <div className="relative">
                            <Input
                              type={showPassword ? "text" : "password"}
                              value={passwordData.password}
                              onChange={(e) =>
                                setPasswordData((prev) => ({
                                  ...prev,
                                  password: e.target.value,
                                }))
                              }
                              className="pr-10 bg-[#ffffff] dark:bg-[#181d26] border-[#dddddd] dark:border-[#333840] focus:ring-[#458fff] focus:border-[#458fff] shadow-sm rounded-[6px]"
                            />
                            <Button
                              type="button"
                              variant="ghost"
                              size="icon"
                              className="absolute right-0 top-0 h-full w-9 text-muted-foreground hover:text-foreground"
                              onClick={() => setShowPassword(!showPassword)}
                            >
                              {showPassword ? (
                                <EyeOff className="h-4 w-4" />
                              ) : (
                                <Eye className="h-4 w-4" />
                              )}
                            </Button>
                          </div>
                        </div>
                        <div className="space-y-2">
                          <Label className="text-[13px] font-medium text-[#41454d] dark:text-[#9297a0]">
                            Xác nhận mật khẩu
                          </Label>
                          <Input
                            type="password"
                            value={passwordData.confirm}
                            onChange={(e) =>
                              setPasswordData((prev) => ({
                                ...prev,
                                confirm: e.target.value,
                              }))
                            }
                            className="bg-[#ffffff] dark:bg-[#181d26] border-[#dddddd] dark:border-[#333840] focus:ring-[#458fff] focus:border-[#458fff] shadow-sm rounded-[6px]"
                          />
                        </div>
                      </div>
                    </div>
                  </div>
                )}

                {error && (
                  <div className="p-4 text-sm text-destructive bg-destructive/5 border border-destructive/20 rounded-md flex items-center gap-2 animate-in fade-in slide-in-from-bottom-2">
                    <Ban className="h-4 w-4" />
                    {error}
                  </div>
                )}
              </div>
            </div>
          </div>
      </DialogContent>
    </Dialog>
  );
}
