"use client";

import * as React from "react";
import Image from "next/image";
import { Customer } from "./types";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
import { ReactSelect } from "@/components/ui/react-select";
import {
  Building2,
  Mail,
  Phone,
  User,
  Users2,
  Upload,
  X,
  Link as LinkIcon,
  History,
  UserCircle,
  MapPin,
  Calendar,
  MessageSquare,
} from "lucide-react";
import { toast } from "sonner";
import { useUpdateCustomerMutation, useGetCustomerBusinessDealsQuery } from "@/api/rtk/customers-api";
import { apiBaseUrl } from "@/api/client";
import { useAuthToken } from "@/hooks/use-auth-token";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { DatePicker } from "@/components/ui/date-picker";
import { BrandSelect } from "@/components/shared/brand-select";
import { AccountTierSelect } from "@/components/shared/account-tier-select";
import { useGetRolesQuery, useGetUserQuery, useGetUsersQuery } from "@/api/rtk";
import type { ApiUser } from "@/api/users/types";
import { pickRoleIdFromOrgRoles } from "@/components/deals/contributor-user-picker";
import { formatTeamLabelForUi } from "@/lib/deal-display";
import { FormSectionHeading, SectionHeading } from "./customer-details-shared";

interface EditCustomerModalProps {
  customer: Customer | null;
  isOpen: boolean;
  onClose: () => void;
  onSuccess?: () => void;
  teams?: { id: string; name: string; color: string }[];
}

const COUNTRIES = ["US", "UK", "CA", "AU", "DE", "FR", "IN", "Other"];

const STATUS_OPTIONS = [
  { value: "Active", label: "Active" },
  { value: "Premium", label: "Premium" },
  { value: "Inactive", label: "Inactive" },
  { value: "Churned", label: "Churned" },
];

const COUNTRY_OPTIONS = COUNTRIES.map((c) => ({ value: c, label: c }));

function FieldLabel({
  children,
  required,
}: {
  children: React.ReactNode;
  required?: boolean;
}) {
  return (
    <label className="block text-[10px] font-bold text-gray-400 uppercase tracking-[0.09em] font-['Lexend_Deca'] mb-1.5 select-none">
      {children}
      {required && <span className="text-red-500 ml-0.5">*</span>}
    </label>
  );
}


export function EditCustomerModal({
  customer,
  isOpen,
  onClose,
  onSuccess,
  teams,
}: EditCustomerModalProps) {
  const [editedCustomer, setEditedCustomer] = React.useState<Customer | null>(
    null,
  );
  const [updateCustomer] = useUpdateCustomerMutation();
  const [selectedImage, setSelectedImage] = React.useState<File | null>(null);
  const [activeTab, setActiveTab] = React.useState("profile");
  const [imagePreview, setImagePreview] = React.useState<string | null>(null);
  const [isSaving, setIsSaving] = React.useState(false);
  const fileInputRef = React.useRef<HTMLInputElement>(null);
  const { token } = useAuthToken();
  const { data: orgRoles = [] } = useGetRolesQuery(undefined, { skip: !isOpen });
  const amRoleId = React.useMemo(
    () =>
      pickRoleIdFromOrgRoles(orgRoles, [
        "am",
        "account manager",
        "AM",
        "Account Manager",
      ]),
    [orgRoles],
  );
  const { data: usersResponse } = useGetUsersQuery(
    { limit: 100, ...(amRoleId ? { roleId: amRoleId } : {}) },
    { skip: !isOpen },
  );
  const usersList = usersResponse?.data;

  const assigneeId = editedCustomer?.assignedAmId?.trim() ?? "";
  const assigneeAlreadyListed =
    !assigneeId || (usersList ?? []).some((u) => u.id === assigneeId);
  const { data: assigneeUser } = useGetUserQuery(assigneeId, {
    skip: !isOpen || assigneeAlreadyListed || !assigneeId,
  });

  const amUsersForSelect = React.useMemo(() => {
    const base = (usersList ?? []).filter((u) => u.name?.toLowerCase() !== "admin");
    const out: ApiUser[] = [...base];
    const link = editedCustomer?.assignedAm;
    const id = editedCustomer?.assignedAmId?.trim();
    if (id && link?.name && !out.some((u) => u.id === id)) {
      out.unshift({
        id,
        name: link.name,
        email: link.email ?? "",
      });
    }
    if (assigneeUser && !out.some((u) => u.id === assigneeUser.id)) {
      out.unshift(assigneeUser);
    }
    return out;
  }, [usersList, assigneeUser, editedCustomer?.assignedAmId, editedCustomer?.assignedAm]);

  const teamOptions = React.useMemo(
    () => [
      { value: "all", label: "No Team" },
      ...(teams?.map((t) => ({
        value: t.name.toLowerCase().split(" ")[1] || t.name.toLowerCase(),
        label: formatTeamLabelForUi(t.name),
      })) ?? []),
    ],
    [teams],
  );

  const amUserOptions = React.useMemo(
    () => amUsersForSelect.map((u) => ({ value: u.id, label: u.name })),
    [amUsersForSelect],
  );

  React.useEffect(() => {
    if (customer) {
      setEditedCustomer({ ...customer });
      setImagePreview(null);
      setSelectedImage(null);
    }
  }, [customer]);

  React.useEffect(() => {
    if (isOpen) setActiveTab("profile");
  }, [isOpen]);

  const { data: customerDeals } = useGetCustomerBusinessDealsQuery(customer?.id ?? "", {
    skip: !isOpen || !customer?.id,
  });

  React.useEffect(() => {
    if (isOpen && customer && customerDeals && (!editedCustomer?.team || editedCustomer.team === "all")) {
      // Find the first deal that has a team assigned
      const suggestedTeam = customerDeals.find(d => d.linkedLead?.team)?.linkedLead?.team;
      if (suggestedTeam) {
        handleUpdate({ team: suggestedTeam.toLowerCase() });
      }
    }
  }, [isOpen, customer, customerDeals]);

  const handleUpdate = (updates: Partial<Customer>) => {
    setEditedCustomer((prev) => (prev ? { ...prev, ...updates } : prev));
  };

  const handleImageSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      if (file.size > 600 * 1024) {
        toast.error("Image size should be less than 600KB");
        return;
      }
      if (!file.type.startsWith("image/")) {
        toast.error("Please select an image file");
        return;
      }
      setSelectedImage(file);
      const reader = new FileReader();
      reader.onloadend = () => {
        setImagePreview(reader.result as string);
      };
      reader.readAsDataURL(file);
    }
  };

  const handleRemoveImage = () => {
    setSelectedImage(null);
    setImagePreview(null);
    if (fileInputRef.current) {
      fileInputRef.current.value = "";
    }
  };

  const handleSave = async () => {
    if (!editedCustomer || !token) return;

    setIsSaving(true);
    try {
      const rawAm = editedCustomer.assignedAmId?.trim();
      const assignedAmIdPayload =
        rawAm && rawAm !== "__" ? rawAm : null;

      const detailData: Record<string, unknown> = {
        fullName: editedCustomer.name,
        companyName: editedCustomer.company,
        email: editedCustomer.email,
        phone: editedCustomer.phone,
        team: editedCustomer.team,
        customerStatus: editedCustomer.status,
        addressUsa: editedCustomer.addressUsa,
        addressIntl: editedCustomer.addressIntl,
        postalCode: editedCustomer.postalCode,
        website: editedCustomer.website,
        country: editedCustomer.country,
        brand: editedCustomer.brand,
        assignedAmId: assignedAmIdPayload,
        accountTier: editedCustomer.accountTier,
        contractExpiryDate: editedCustomer.contractExpiryDate,
        npsScore:
          editedCustomer.npsScore != null
            ? Number(editedCustomer.npsScore)
            : undefined,
        npsDate: editedCustomer.npsDate,
        notes: editedCustomer.notes,
      };

      if (selectedImage) {
        const formData = new FormData();
        Object.entries(detailData).forEach(([key, value]) => {
          if (value === undefined) return;
          if (key === "assignedAmId") {
            formData.append(
              key,
              value === null || value === "" ? "" : String(value),
            );
            return;
          }
          if (value !== null) {
            formData.append(key, value.toString());
          }
        });
        formData.append("file", selectedImage);

        const response = await fetch(
          `${apiBaseUrl}/customers/${editedCustomer.id}`,
          {
            method: "PATCH",
            headers: {
              Authorization: `Bearer ${token}`,
            },
            body: formData,
          },
        );

        if (!response.ok) {
          const errorData = await response.json().catch(() => ({}));
          throw new Error(
            (errorData as { error?: { message?: string[] }; message?: string })
              .error?.message?.[0] ||
            (errorData as { message?: string }).message ||
            "Failed to update customer profile",
          );
        }
      } else {
        await updateCustomer({
          id: editedCustomer.id,
          updates: detailData,
        }).unwrap();
      }

      toast.success("Customer updated successfully");
      onSuccess?.();
      onClose();
    } catch (error: any) {
      console.error("Failed to update customer:", error);
      toast.error(error.message || "Failed to update customer");
    } finally {
      setIsSaving(false);
    }
  };

  if (!isOpen || !editedCustomer) return null;

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="sm:max-w-[800px] w-[96vw] max-h-[90vh] p-0 overflow-hidden animate-in zoom-in-95 duration-200">
        {/* HEADER */}
        <div className="relative overflow-hidden">
          <div className="absolute inset-0 bg-linear-to-br from-[#6C63FF] via-[#7C74FF] to-[#9B8FFF] opacity-100" />
          <div className="absolute inset-0 bg-[radial-gradient(ellipse_at_top_right,rgba(255,255,255,0.12),transparent_60%)]" />

          <div className="relative px-7 py-5 flex items-start justify-between gap-4">
            <div className="flex items-center gap-4 min-w-0">
              <div className="h-12 w-12 rounded-xl bg-white/15 border border-white/25 backdrop-blur-sm flex items-center justify-center shrink-0 shadow-inner">
                <Building2 size={22} className="text-white/90" />
              </div>
              <div className="min-w-0">
                <DialogTitle className="text-[20px] font-extrabold text-white font-['Lexend'] leading-tight truncate">
                  Edit Customer
                </DialogTitle>
                <div className="flex items-center gap-2 mt-1 flex-wrap">
                  <span className="text-[12px] text-white/75 font-medium">
                    {editedCustomer.name}
                  </span>
                  {editedCustomer.team && (
                    <>
                      <span className="text-white/30">·</span>
                      <span className="text-[12px] text-white/75 font-medium">
                        {formatTeamLabelForUi(editedCustomer.team)}
                      </span>
                    </>
                  )}
                </div>
              </div>
            </div>

            <div className="bg-white/10 border border-white/20 rounded-xl px-4 py-2.5 text-center backdrop-blur-sm shrink-0">
              <p className="text-[10px] font-bold text-white/60 uppercase tracking-widest font-['Lexend_Deca']">
                Status
              </p>
              <p className="text-[14px] font-extrabold text-white font-['Lexend'] leading-tight">
                {editedCustomer.status}
              </p>
            </div>
          </div>
        </div>

        {/* BODY */}
        <div className="overflow-y-auto max-h-[calc(90vh-200px)] scrollbar-themed">
          <Tabs
            value={activeTab}
            onValueChange={setActiveTab}
            className="w-full"
          >
            <div className="px-7 pt-4 pb-2 border-b border-gray-100 bg-gray-50/30">
              <TabsList
                variant="line"
                className="w-full justify-start gap-6 h-10 p-0"
              >
                <TabsTrigger
                  value="profile"
                  className="data-[state=active]:after:bg-[#6C63FF] px-0 gap-2 text-xs tracking-wider"
                >
                  <UserCircle size={16} /> PROFILE DETAILS
                </TabsTrigger>
                <TabsTrigger
                  value="timeline"
                  className="data-[state=active]:after:bg-[#6C63FF] px-0 gap-2 text-xs tracking-wider"
                >
                  <History size={16} /> ACTIVITY TIMELINE
                </TabsTrigger>
              </TabsList>
            </div>

            <div className="px-7 py-6">
              <TabsContent value="profile" className="m-0 space-y-6">
                {/* Profile Image Section */}
                <section>
                  <FormSectionHeading icon={<Upload size={14} />}>
                    Profile Image (Optional)
                  </FormSectionHeading>
                  <div className="flex items-center gap-4">
                    <div className="relative">
                      <div className="relative h-24 w-24 rounded-full bg-gradient-to-br from-[#6C63FF] to-[#8B83FF] flex items-center justify-center text-white text-2xl font-black shadow-lg overflow-hidden">
                        {imagePreview ? (
                          <Image
                            src={imagePreview}
                            alt="Preview"
                            fill
                            sizes="96px"
                            className="object-cover"
                            unoptimized={
                              imagePreview.startsWith("blob:") ||
                              imagePreview.startsWith("data:")
                            }
                          />
                        ) : editedCustomer.avatarUrl ? (
                          <Image
                            src={editedCustomer.avatarUrl}
                            alt={editedCustomer.name}
                            fill
                            sizes="96px"
                            className="object-cover"
                            unoptimized={
                              editedCustomer.avatarUrl.startsWith(
                                "blob:",
                              ) ||
                              editedCustomer.avatarUrl.startsWith("data:")
                            }
                          />
                        ) : (
                          editedCustomer.initials ||
                          editedCustomer.name?.slice(0, 2).toUpperCase()
                        )}
                      </div>
                      {(imagePreview || selectedImage) && (
                        <button
                          onClick={handleRemoveImage}
                          className="absolute -top-1 -right-1 h-6 w-6 rounded-full bg-red-500 text-white flex items-center justify-center hover:bg-red-600 transition-colors"
                        >
                          <X size={14} />
                        </button>
                      )}
                    </div>
                    <div className="flex-1">
                      <input
                        ref={fileInputRef}
                        type="file"
                        accept="image/*"
                        onChange={handleImageSelect}
                        className="hidden"
                        id="customer-image-upload"
                      />
                      <label
                        htmlFor="customer-image-upload"
                        className="inline-flex items-center gap-2 px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-xl cursor-pointer transition-colors text-[13px] font-semibold text-gray-700"
                      >
                        <Upload size={14} />
                        {selectedImage ? "Change Image" : "Upload Image"}
                      </label>
                      <p className="text-[11px] text-gray-500 mt-2 font-['Lexend_Deca']">
                        JPG, PNG or GIF. Max size 600KB.
                      </p>
                    </div>
                  </div>
                </section>

                <section>
                  <FormSectionHeading icon={<User size={14} />}>
                    Customer Information
                  </FormSectionHeading>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <FieldLabel>Customer Name</FieldLabel>
                      <Input
                        className="h-10 text-[14px] font-semibold bg-gray-50 border-gray-200 rounded-xl"
                        value={editedCustomer.name || ""}
                        onChange={(e) => handleUpdate({ name: e.target.value })}
                      />
                    </div>
                    <div>
                      <FieldLabel>Company</FieldLabel>
                      <Input
                        className="h-10 text-[14px] bg-gray-50 border-gray-200 rounded-xl"
                        value={editedCustomer.company || ""}
                        onChange={(e) =>
                          handleUpdate({ company: e.target.value })
                        }
                      />
                    </div>
                    <div>
                      <FieldLabel>Email</FieldLabel>
                      <div className="relative">
                        <Mail
                          size={14}
                          className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"
                        />
                        <Input
                          className="h-10 text-[14px] bg-gray-50 border-gray-200 rounded-xl pl-9"
                          value={editedCustomer.email || ""}
                          onChange={(e) =>
                            handleUpdate({ email: e.target.value })
                          }
                        />
                      </div>
                    </div>
                    <div>
                      <FieldLabel>Phone</FieldLabel>
                      <div className="relative">
                        <Phone
                          size={14}
                          className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"
                        />
                        <Input
                          className="h-10 text-[14px] bg-gray-50 border-gray-200 rounded-xl pl-9"
                          value={editedCustomer.phone || ""}
                          onChange={(e) =>
                            handleUpdate({ phone: e.target.value })
                          }
                        />
                      </div>
                    </div>
                  </div>
                </section>

                <section>
                  <FormSectionHeading icon={<Users2 size={14} />}>
                    Team & Status
                  </FormSectionHeading>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <FieldLabel>Team</FieldLabel>
                      <ReactSelect
                        value={editedCustomer.team || "all"}
                        onValueChange={(val) =>
                          handleUpdate({ team: val === "all" ? "" : val })
                        }
                        options={teamOptions}
                        triggerClassName="h-10 min-h-10 bg-gray-50 border-gray-200 rounded-xl text-[13px] font-semibold"
                        contentClassName="rounded-xl"
                      />
                    </div>
                    <div>
                      <FieldLabel>Status</FieldLabel>
                      <ReactSelect
                        value={editedCustomer.status}
                        onValueChange={(val) =>
                          handleUpdate({ status: val as Customer["status"] })
                        }
                        options={STATUS_OPTIONS}
                        triggerClassName="h-10 min-h-10 bg-gray-50 border-gray-200 rounded-xl text-[13px] font-semibold"
                        contentClassName="rounded-xl"
                      />
                    </div>
                  </div>
                </section>

                <section>
                  <FormSectionHeading icon={<MapPin size={14} />}>
                    Address & Location
                  </FormSectionHeading>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <FieldLabel>US address</FieldLabel>
                      <Input
                        className="h-10 text-[14px] bg-gray-50 border-gray-200 rounded-xl"
                        value={editedCustomer.addressUsa ?? ""}
                        onChange={(e) =>
                          handleUpdate({ addressUsa: e.target.value })
                        }
                        placeholder="US address"
                      />
                    </div>
                    <div>
                      <FieldLabel>International address</FieldLabel>
                      <Input
                        className="h-10 text-[14px] bg-gray-50 border-gray-200 rounded-xl"
                        value={editedCustomer.addressIntl ?? ""}
                        onChange={(e) =>
                          handleUpdate({ addressIntl: e.target.value })
                        }
                        placeholder="CA/UK/other"
                      />
                    </div>
                    <div>
                      <FieldLabel>Postal code</FieldLabel>
                      <Input
                        className="h-10 text-[14px] bg-gray-50 border-gray-200 rounded-xl"
                        value={editedCustomer.postalCode ?? ""}
                        onChange={(e) =>
                          handleUpdate({ postalCode: e.target.value })
                        }
                        placeholder="Postal code"
                      />
                    </div>
                    <div>
                      <FieldLabel>Country</FieldLabel>
                      <ReactSelect
                        value={editedCustomer.country ?? ""}
                        onValueChange={(v) => handleUpdate({ country: v })}
                        options={COUNTRY_OPTIONS}
                        placeholder="Select country"
                        allowEmpty
                        triggerClassName="h-10 min-h-10 bg-gray-50 border-gray-200 rounded-xl text-[13px]"
                        contentClassName="rounded-xl"
                      />
                    </div>
                    <div className="col-span-2">
                      <FieldLabel>Website</FieldLabel>
                      <div className="relative">
                        <LinkIcon
                          size={14}
                          className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"
                        />
                        <Input
                          type="url"
                          className="h-10 text-[14px] bg-gray-50 border-gray-200 rounded-xl pl-9"
                          value={editedCustomer.website ?? ""}
                          onChange={(e) =>
                            handleUpdate({ website: e.target.value })
                          }
                          placeholder="https://company.com"
                        />
                      </div>
                    </div>
                  </div>
                </section>

                <section>
                  <FormSectionHeading icon={<Building2 size={14} />}>
                    Brand & Assignment
                  </FormSectionHeading>
                  <div className="grid grid-cols-2 gap-4">
                    <div className="col-span-2 sm:col-span-1">
                      <BrandSelect
                        value={editedCustomer.brand ?? ""}
                        onValueChange={(v) => handleUpdate({ brand: v })}
                        label="Brand"
                        placeholder="Select brand"
                        allowEmpty
                        triggerClassName="h-10 bg-gray-50 border-gray-200 rounded-xl text-[13px]"
                      />
                    </div>
                    <div>
                      <FieldLabel>Assigned AM</FieldLabel>
                      <ReactSelect
                        value={editedCustomer.assignedAmId ?? ""}
                        onValueChange={(v) => handleUpdate({ assignedAmId: v })}
                        options={amUserOptions}
                        placeholder="Select AM"
                        allowEmpty
                        triggerClassName="h-10 min-h-10 bg-gray-50 border-gray-200 rounded-xl text-[13px]"
                        contentClassName="rounded-xl"
                      />
                    </div>
                    <div>
                      <AccountTierSelect
                        value={editedCustomer.accountTier ?? ""}
                        onValueChange={(v) => handleUpdate({ accountTier: v })}
                        label="Account tier"
                        placeholder="Select account tier"
                        allowEmpty
                        skip={!isOpen}
                        triggerClassName="h-10 bg-gray-50 border-gray-200 rounded-xl text-[13px]"
                      />
                    </div>
                  </div>
                </section>

                <section>
                  <FormSectionHeading icon={<Calendar size={14} />}>
                    Contract & NPS
                  </FormSectionHeading>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <FieldLabel>Contract expiry date</FieldLabel>
                      <DatePicker
                        value={editedCustomer.contractExpiryDate}
                        onChange={(val: string | undefined) =>
                          handleUpdate({ contractExpiryDate: val })
                        }
                        triggerClassName="h-10 text-[14px] bg-gray-50 border-gray-200 rounded-xl"
                      />
                    </div>
                    <div>
                      <FieldLabel>NPS score (0–10)</FieldLabel>
                      <Input
                        type="number"
                        min={0}
                        max={10}
                        className="h-10 text-[14px] bg-gray-50 border-gray-200 rounded-xl"
                        value={editedCustomer.npsScore ?? ""}
                        onChange={(e) =>
                          handleUpdate({
                            npsScore:
                              e.target.value === ""
                                ? undefined
                                : Number(e.target.value),
                          })
                        }
                        placeholder="0–10"
                      />
                    </div>
                    <div>
                      <FieldLabel>NPS date</FieldLabel>
                      <DatePicker
                        value={editedCustomer.npsDate}
                        onChange={(val: string | undefined) =>
                          handleUpdate({ npsDate: val })
                        }
                        triggerClassName="h-10 text-[14px] bg-gray-50 border-gray-200 rounded-xl"
                      />
                    </div>
                  </div>
                </section>

                <section>
                  <FormSectionHeading icon={<MessageSquare size={14} />}>
                    Notes
                  </FormSectionHeading>
                  <Textarea
                    className="min-h-[80px] text-[14px] bg-gray-50 border-gray-200 rounded-xl resize-y"
                    value={editedCustomer.notes ?? ""}
                    onChange={(e) => handleUpdate({ notes: e.target.value })}
                    placeholder="Relationship intelligence: champions, sceptics, sensitivities"
                  />
                </section>
              </TabsContent>

              <TabsContent
                value="timeline"
                className="m-0 min-h-[400px] flex flex-col items-center justify-center text-center p-8 bg-gray-50/50 rounded-2xl border border-dashed border-gray-200"
              >
                <div className="h-16 w-16 rounded-2xl bg-white flex items-center justify-center text-gray-400 shadow-sm mb-4">
                  <History size={32} />
                </div>
                <h3 className="text-[16px] font-bold text-gray-900 mb-1">
                  Activity Timeline Coming Soon
                </h3>
                <p className="text-[13px] text-gray-500 max-w-[280px]">
                  View a full history of interactions, notes, and status changes
                  for {editedCustomer.name}.
                </p>
              </TabsContent>
            </div>
          </Tabs>
        </div>

        {/* FOOTER */}
        <div className="border-t border-gray-100 px-7 py-4 flex items-center justify-end gap-3 bg-gray-50/50">
          <Button
            variant="outline"
            onClick={onClose}
            disabled={isSaving}
            className="h-10 px-6 rounded-xl font-semibold"
          >
            Cancel
          </Button>
          <Button
            onClick={handleSave}
            disabled={isSaving}
            className="h-10 px-6 rounded-xl font-semibold bg-[#6C63FF] hover:bg-[#5a52e0]"
          >
            {isSaving ? "Saving..." : "Save Changes"}
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  );
}
