"use client";

import { useEffect, useState, useCallback } from "react";
import {
  Briefcase,
  Phone,
  MapPin,
  User,
  ClipboardList,
  Pencil,
  Trash2,
  Search,
  Check,
  Mail,
  X,
  UserPlus,
  Loader2,
} from "lucide-react";
import PageHeader from "@/components/modals/ui/PageHeader";
import { Hospital } from "@/app/types/medicalData";
import { useRouter } from "next/navigation";
import axiosInstance from "@/app/services/api";
import { apiUrl } from "@/app/services/endpoints";
import {
  deleteHospitalApi,
  myHospitalsApi,
  updateHospitalApi,
  inviteMemberApi,
} from "@/app/services/hospial";
import { Country } from "country-state-city";

const ALL_COUNTRIES = Country.getAllCountries().map((country) => ({
  code: country.isoCode,
  name: country.name,
  flag: `https://flagcdn.com/w40/${country.isoCode.toLowerCase()}.png`,
}));

const HOSPITAL_TYPES = [
  "Clinic",
  "Hospital",
  "Nursing Home",
  "Diagnostic Centre",
];

const setDefaultHospitalApi = async (hospitalId: string) => {
  const res = await axiosInstance.patch(apiUrl.setDefaultHospital(hospitalId));
  return res.data;
};

export default function HospitalDetailsPage({
  hospitalId,
  onClose,
}: {
  hospitalId?: string;
  onClose?: () => void;
}) {
  const router = useRouter();
  const [hospital, setHospital] = useState<Hospital | null>(null);

  const [view, setView] = useState<"details" | "edit">("details");
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [showCountryModal, setShowCountryModal] = useState(false);
  const [countrySearch, setCountrySearch] = useState("");

  // ── Add Member state ──
  const [showAddMemberModal, setShowAddMemberModal] = useState(false);
  const [inviteEmail, setInviteEmail] = useState("");
  const [inviteLoading, setInviteLoading] = useState(false);
  const [inviteError, setInviteError] = useState<string | null>(null);
  const [inviteSuccess, setInviteSuccess] = useState(false);

  // ── Set Default state ──
  const [settingDefault, setSettingDefault] = useState(false);
  const [setDefaultError, setSetDefaultError] = useState<string | null>(null);

  const [formData, setFormData] = useState({
    name: "",
    type: "Clinic",
    licenseNo: "",
    phone: "",
    email: "",
    country: {
      code: "IN",
      name: "India",
      flag: "https://flagcdn.com/w40/in.png",
    },
    state: "",
    city: "",
    pincode: "",
    address: "",
  });

  const fetchHospital = useCallback(async () => {
    try {
      if (!hospitalId) return;

      const res = await myHospitalsApi();
      const foundHospital = res.data.find(
        (h: Hospital) => h._id === hospitalId,
      );

      if (foundHospital) {
        setHospital(foundHospital);
        const matchedCountry = ALL_COUNTRIES.find(
          (c) =>
            c.name.toLowerCase() === foundHospital.country?.toLowerCase(),
        );

        setFormData({
          name: foundHospital.name || "",
          type: foundHospital.type || "Clinic",
          licenseNo: foundHospital.licenseNo || "",
          phone: foundHospital.phone || "",
          email: foundHospital.email || "",
          country: matchedCountry || {
            code: "IN",
            name: "India",
            flag: "https://flagcdn.com/w40/in.png",
          },
          state: foundHospital.state || "",
          city: foundHospital.city || "",
          pincode: foundHospital.pincode || "",
          address: foundHospital.address || "",
        });
      }
    } catch (error) {
      console.error("Error loading hospital:", error);
    }
  }, [hospitalId]);

  useEffect(() => {
    fetchHospital();
  }, [fetchHospital]);

  if (!hospital) {
    return (
      <div className="min-h-screen flex items-center justify-center text-gray-500 font-medium">
        Loading details...
      </div>
    );
  }

  const handleDelete = async () => {
    try {
      const res = await deleteHospitalApi(hospital._id);
      if (res?.status === 1) {
        onClose?.();
      }
    } catch (error) {
      console.log(error);
    }
  };

  const handleSaveEdit = async () => {
    const payload = {
      name: formData.name,
      type: formData.type,
      licenseNo: formData.licenseNo,
      phone: formData.phone,
      email: formData.email,
      country: formData.country.name,
      state: formData.state,
      city: formData.city,
      pincode: formData.pincode,
      address: formData.address,
    };

    try {
      const res = await updateHospitalApi(hospital._id, payload);
      if (res?.status === 1) {
        const updatedHospital = { ...hospital, ...payload };
        setHospital(updatedHospital as any);
        setView("details");
      }
    } catch (error) {
      console.log(error);
    }
  };

  // ── Invite member handler ──
  const handleInviteMember = async () => {
    if (!inviteEmail.trim()) {
      setInviteError("Please enter an email address");
      return;
    }

    // basic email format check
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(inviteEmail.trim())) {
      setInviteError("Please enter a valid email address");
      return;
    }

    try {
      setInviteLoading(true);
      setInviteError(null);

      const res = await inviteMemberApi(hospital._id, inviteEmail.trim());

      if (res?.status === 1) {
        setInviteSuccess(true);
        setInviteEmail("");
        setTimeout(() => {
          setShowAddMemberModal(false);
          setInviteSuccess(false);
        }, 1200);
      } else {
        setInviteError(res?.msg || "Failed to invite member");
      }
    } catch (error: any) {
      setInviteError(
        error?.response?.data?.msg ||
        error?.message ||
        "Failed to invite member",
      );
    } finally {
      setInviteLoading(false);
    }
  };

  const closeAddMemberModal = () => {
    setShowAddMemberModal(false);
    setInviteEmail("");
    setInviteError(null);
    setInviteSuccess(false);
  };

  // ── Set Default handler ──
  const handleSetDefault = async () => {
    try {
      setSettingDefault(true);
      setSetDefaultError(null);

      const res = await setDefaultHospitalApi(hospital._id);

      if (res?.status === 1) {
        await fetchHospital();
      } else {
        setSetDefaultError(res?.msg || "Failed to set as default");
      }
    } catch (error: any) {
      setSetDefaultError(
        error?.response?.data?.msg ||
        error?.message ||
        "Failed to set as default",
      );
    } finally {
      setSettingDefault(false);
    }
  };

  const defaultMember = hospital.members?.find((member) => member.isDefault);
  const isDefaultHospital = !!defaultMember?.isDefault;
  const filteredCountries = ALL_COUNTRIES.filter((c) =>
    c.name.toLowerCase().includes(countrySearch.toLowerCase()),
  );

  return (
    <div className="min-h-screen bg-[#f7f7f8] pb-24">
      {/* ── HEADER ── */}
      <PageHeader
        icon={<Briefcase size={20} />}
        title={view === "edit" ? "Edit Hospital" : hospital.name}
        subtitle={
          view === "edit"
            ? "Update your hospital or clinic details"
            : "View hospital information"
        }
      />

      <main className="max-w-[760px] mx-auto p-5 sm:p-7 flex flex-col gap-4">
        {view === "details" && (
          <div className="flex flex-col gap-4 animate-in fade-in duration-300">
            {/* 1. Hospital Details Card */}
            <div className="bg-white rounded-[24px] border border-[#e5e7eb] shadow-sm p-5">
              <div className="flex items-center justify-between mb-5">
                <SectionHeading
                  icon={<Briefcase size={18} />}
                  iconColorClass="text-[#6366f1]"
                  iconBgClass="bg-[#eef2ff]"
                  title="Hospital Details"
                  noMargin
                />
                <div className="flex items-center gap-3">
                  {isDefaultHospital && (
                    <span className="px-3 py-1 rounded-full border border-[#22c55e] text-[#22c55e] text-xs font-medium bg-white">
                      Default
                    </span>
                  )}
                  <button
                    onClick={() => setView("edit")}
                    className="w-8 h-8 rounded-full bg-[#f3f4f6] hover:bg-[#e5e7eb] transition-colors flex items-center justify-center border-none cursor-pointer"
                  >
                    <Pencil size={14} className="text-[#6366f1]" />
                  </button>
                </div>
              </div>
              <div className="flex flex-col gap-5">
                <InfoRow
                  icon={<Briefcase size={20} />}
                  label="Name"
                  value={hospital.name}
                  iconColor="text-[#6366f1]"
                />
                <InfoRow
                  icon={<Briefcase size={20} />}
                  label="Type"
                  value={hospital.type}
                  iconColor="text-[#6366f1]"
                />
                <InfoRow
                  icon={<ClipboardList size={20} />}
                  label="License / Registration No."
                  value={hospital.licenseNo || "N/A"}
                  iconColor="text-[#6366f1]"
                />
              </div>
            </div>

            {/* 2. Contact Card */}
            <div className="bg-white rounded-[24px] border border-[#e5e7eb] shadow-sm p-5">
              <SectionHeading
                icon={<Phone size={18} />}
                iconColorClass="text-[#16a34a]"
                iconBgClass="bg-[#e8f8ee]"
                title="Contact"
              />
              <div className="flex flex-col gap-5">
                <InfoRow
                  icon={<Phone size={20} />}
                  label="Phone"
                  value={hospital.phone}
                  iconColor="text-[#16a34a]"
                />
                {hospital.email && (
                  <InfoRow
                    icon={<Mail size={20} />}
                    label="Email"
                    value={hospital.email}
                    iconColor="text-[#16a34a]"
                  />
                )}
              </div>
            </div>

            {/* 3. Location Card */}
            <div className="bg-white rounded-[24px] border border-[#e5e7eb] shadow-sm p-5">
              <SectionHeading
                icon={<MapPin size={18} />}
                iconColorClass="text-[#eab308]"
                iconBgClass="bg-[#fef9c3]"
                title="Location"
              />
              <div className="flex flex-col gap-5">
                <InfoRow
                  icon={<MapPin size={20} />}
                  label="Street Address"
                  value={hospital.address}
                  iconColor="text-[#eab308]"
                />
                <InfoRow
                  icon={<MapPin size={20} />}
                  label="City, State"
                  value={`${hospital.city}, ${hospital.state}`}
                  iconColor="text-[#eab308]"
                />
                <InfoRow
                  icon={<MapPin size={20} />}
                  label="Country, Pincode"
                  value={`${hospital.country} - ${hospital.pincode}`}
                  iconColor="text-[#eab308]"
                />
              </div>
            </div>

            {/* 3.5 Set as Default Button — only shown when this hospital is NOT default */}
            {!isDefaultHospital && (
              <div className="flex flex-col gap-2">
                <button
                  onClick={handleSetDefault}
                  disabled={settingDefault}
                  className="w-full bg-[#4f46e5] hover:bg-[#4338ca] disabled:opacity-60 transition-colors text-white py-4 rounded-[20px] font-medium text-base flex items-center justify-center gap-2 shadow-sm cursor-pointer border-none"
                >
                  {settingDefault ? (
                    <>
                      <Loader2 size={20} className="animate-spin" />
                      Setting as default...
                    </>
                  ) : (
                    <>
                      <Briefcase size={20} />
                      Set as Default
                    </>
                  )}
                </button>
                {setDefaultError && (
                  <p className="text-sm text-red-500 text-center px-2">
                    {setDefaultError}
                  </p>
                )}
              </div>
            )}

            {/* 4. Members Card */}
            <div className="bg-white rounded-[24px] border border-[#e5e7eb] shadow-sm p-5">
              <div className="flex items-center justify-between mb-5">
                <SectionHeading
                  icon={<User size={18} />}
                  iconColorClass="text-[#10b981]"
                  iconBgClass="bg-[#d1fae5]"
                  title="Members"
                  noMargin
                />
                <button
                  type="button"
                  onClick={() => setShowAddMemberModal(true)}
                  className="flex items-center gap-1.5 px-3 py-2 rounded-full bg-[#eef2ff] hover:bg-[#e0e7ff] text-[#4f46e5] text-xs font-medium transition-colors cursor-pointer border-none"
                >
                  <UserPlus size={14} />
                  Add Member
                </button>
              </div>
              <div className="flex flex-col gap-3">
                {hospital.members && hospital.members.length > 0 ? (
                  hospital.members.map((member: any) => (
                    <div
                      key={member._id}
                      className="flex items-center justify-between bg-[#f8fafc] rounded-2xl p-4 border border-[#f1f5f9]"
                    >
                      <div className="flex items-center gap-4">
                        <div className="w-10 h-10 rounded-full bg-[#e0e7ff] flex items-center justify-center text-[#4f46e5]">
                          <User size={20} />
                        </div>
                        <p className="text-[15px] font-medium text-[#111111]">
                          {member.user?.fullname ||
                            member.fullname ||
                            member.name ||
                            "Unknown Member"}
                        </p>
                      </div>
                      {member.isAdmin && (
                        <span className="text-[11px] font-medium text-[#4f46e5] bg-white border border-[#e5e7eb] px-3 py-1.5 rounded-full shadow-sm">
                          Admin
                        </span>
                      )}
                    </div>
                  ))
                ) : (
                  <p className="text-sm text-gray-500 px-2">
                    No members found.
                  </p>
                )}
              </div>
            </div>

            {/* 5. Delete Button */}
            <button
              onClick={() => setShowDeleteModal(true)}
              className="w-full bg-[#dc2626] hover:bg-[#b91c1c] transition-colors text-white py-4 rounded-[20px] font-medium text-base flex items-center justify-center gap-2 shadow-sm mt-2 cursor-pointer border-none"
            >
              <Trash2 size={20} />
              Delete Clinic
            </button>
          </div>
        )}
        {view === "edit" && (
          <div className="flex flex-col gap-4 animate-in fade-in duration-300">
            {/* Form Section 1: Details */}
            <div className="bg-white rounded-[24px] border border-[#e5e7eb] shadow-sm p-5">
              <SectionHeading
                icon={<Briefcase size={18} />}
                iconColorClass="text-[#6366f1]"
                iconBgClass="bg-[#eef2ff]"
                title="Hospital Details"
              />

              <div className="flex flex-col gap-4">
                <CustomInput
                  icon={<Briefcase size={18} />}
                  label="Hospital / Clinic name *"
                  value={formData.name}
                  onChange={(e) =>
                    setFormData({ ...formData, name: e.target.value })
                  }
                  iconColor="text-[#6366f1]"
                />

                <div>
                  <p className="text-sm font-medium text-[#4b5563] mb-2">
                    Type
                  </p>
                  <div className="flex flex-wrap gap-2">
                    {HOSPITAL_TYPES.map((t) => {
                      const isActive = formData.type === t;
                      return (
                        <button
                          key={t}
                          onClick={() => setFormData({ ...formData, type: t })}
                          className={`flex items-center gap-2 px-4 py-2.5 rounded-xl border text-sm font-medium transition-all cursor-pointer ${isActive
                            ? "bg-[#f3e8ff] border-[#e9d5ff] text-[#7e22ce]"
                            : "bg-[#f9fafb] border-[#e5e7eb] text-[#4b5563] hover:bg-[#f3f4f6]"
                            }`}
                        >
                          {isActive && <Check size={16} />}
                          {t}
                        </button>
                      );
                    })}
                  </div>
                </div>

                <CustomInput
                  icon={<ClipboardList size={18} />}
                  label="License / Registration no. (optional)"
                  value={formData.licenseNo}
                  onChange={(e) =>
                    setFormData({ ...formData, licenseNo: e.target.value })
                  }
                  iconColor="text-[#6366f1]"
                />
              </div>
            </div>

            {/* Form Section 2: Contact */}
            <div className="bg-white rounded-[24px] border border-[#e5e7eb] shadow-sm p-5">
              <SectionHeading
                icon={<Phone size={18} />}
                iconColorClass="text-[#16a34a]"
                iconBgClass="bg-[#e8f8ee]"
                title="Contact"
              />
              <div className="flex flex-col gap-4">
                <CustomInput
                  icon={<Phone size={18} />}
                  label="Hospital phone (optional)"
                  value={formData.phone}
                  onChange={(e) =>
                    setFormData({ ...formData, phone: e.target.value })
                  }
                  iconColor="text-[#16a34a]"
                />
                <CustomInput
                  icon={<Mail size={18} />}
                  label="Hospital email (optional)"
                  value={formData.email}
                  onChange={(e) =>
                    setFormData({ ...formData, email: e.target.value })
                  }
                  iconColor="text-[#16a34a]"
                />
              </div>
            </div>

            {/* Form Section 3: Location */}
            <div className="bg-white rounded-[24px] border border-[#e5e7eb] shadow-sm p-5">
              <SectionHeading
                icon={<MapPin size={18} />}
                iconColorClass="text-[#eab308]"
                iconBgClass="bg-[#fef9c3]"
                title="Location"
              />
              <div className="flex flex-col gap-4">
                {/* Country Trigger Button */}
                <button
                  type="button"
                  onClick={() => setShowCountryModal(true)}
                  className="w-full relative flex items-center gap-3 rounded-xl border border-[#e5e7eb] bg-white px-4 py-3.5 transition-colors text-left cursor-pointer hover:bg-[#f7f7f8]"
                >
                  <span className="text-[#eab308] flex-shrink-0">
                    <MapPin size={18} />
                  </span>
                  <div className="flex-1">
                    <p className="text-sm font-medium text-[#4b5563] mb-0.5">
                      Country
                    </p>
                    <p className="text-base text-[#111111] flex items-center gap-2">
                      <img
                        src={formData.country.flag}
                        alt={formData.country.name}
                        className="w-6 h-4 object-cover rounded shadow-sm bg-gray-200"
                      />
                      {formData.country.name} ({formData.country.code})
                      <span className="ml-1 text-xs text-[#9ca3af]">▼</span>
                    </p>
                  </div>
                </button>

                <CustomInput
                  icon={<MapPin size={18} />}
                  label="State"
                  value={formData.state}
                  onChange={(e) =>
                    setFormData({ ...formData, state: e.target.value })
                  }
                  iconColor="text-[#eab308]"
                />

                <div className="flex gap-4">
                  <div className="flex-1">
                    <CustomInput
                      icon={<MapPin size={18} />}
                      label="City"
                      value={formData.city}
                      onChange={(e) =>
                        setFormData({ ...formData, city: e.target.value })
                      }
                      iconColor="text-[#eab308]"
                    />
                  </div>
                  <div className="flex-1">
                    <CustomInput
                      icon={<MapPin size={18} className="rotate-180" />}
                      label="Pincode"
                      value={formData.pincode}
                      onChange={(e) =>
                        setFormData({ ...formData, pincode: e.target.value })
                      }
                      iconColor="text-[#eab308]"
                    />
                  </div>
                </div>

                <CustomInput
                  icon={<MapPin size={18} />}
                  label="Street address *"
                  value={formData.address}
                  onChange={(e) =>
                    setFormData({ ...formData, address: e.target.value })
                  }
                  iconColor="text-[#eab308]"
                />
              </div>
            </div>

            {/* Bottom Fixed Action Bar */}
            <div className="fixed bottom-0 left-0 right-0 p-5 bg-white border-t border-[#e5e7eb] z-10 flex justify-center">
              <div className="w-full max-w-[760px] flex gap-3">
                <button
                  onClick={() => setView("details")}
                  className="flex-1 bg-[#f3f4f6] hover:bg-[#e5e7eb] text-[#4b5563] py-4 rounded-[20px] font-medium text-base transition-colors cursor-pointer border-none"
                >
                  Cancel
                </button>
                <button
                  onClick={handleSaveEdit}
                  className="flex-[2] bg-[#4f46e5] hover:bg-[#4338ca] text-white py-4 rounded-[20px] font-medium text-base transition-colors shadow-md border-none cursor-pointer"
                >
                  Save Changes
                </button>
              </div>
            </div>
          </div>
        )}
      </main>

      {/* 1. Custom Delete Confirmation Modal */}
      {showDeleteModal && (
        <div className="fixed inset-0 z-50 flex items-end justify-center sm:items-center">
          <div
            className="absolute inset-0 bg-black/40 transition-opacity"
            onClick={() => setShowDeleteModal(false)}
          />
          <div className="relative bg-white w-full sm:max-w-[400px] rounded-t-[32px] sm:rounded-[32px] p-8 text-center animate-in slide-in-from-bottom-10 sm:slide-in-from-bottom-0 sm:fade-in duration-200">
            <h3 className="text-xl font-medium text-[#111111] mb-3">
              Delete Hospital?
            </h3>
            <p className="text-[#6b7280] text-[15px] leading-relaxed mb-8 px-2">
              Are you sure you want to delete{" "}
              <span className="font-medium text-gray-900">
                {hospital.name}
              </span>
              ? This action cannot be undone.
            </p>
            <div className="flex gap-3">
              <button
                onClick={() => setShowDeleteModal(false)}
                className="flex-1 bg-[#8b8fa3] hover:bg-[#7a7e91] text-white py-4 rounded-[20px] font-medium text-base transition-colors cursor-pointer border-none"
              >
                Cancel
              </button>
              <button
                onClick={() => {
                  setShowDeleteModal(false);
                  handleDelete();
                }}
                className="flex-1 bg-[#f472b6] hover:bg-[#ec4899] text-white py-4 rounded-[20px] font-medium text-base transition-colors shadow-sm cursor-pointer border-none"
              >
                Yes
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 2. Country Picker Modal */}
      {showCountryModal && (
        <div className="fixed inset-0 z-[200] flex items-end justify-center sm:items-center bg-black/40 transition-opacity">
          <div className="relative bg-white w-full h-[85vh] sm:h-auto sm:max-h-[80vh] sm:max-w-[480px] flex flex-col rounded-t-[32px] sm:rounded-3xl overflow-hidden animate-in slide-in-from-bottom-10 sm:slide-in-from-bottom-0 sm:fade-in duration-200 shadow-xl">
            <div className="p-5 border-b border-[#f3f4f6] shrink-0">
              <div className="flex items-center justify-between mb-4">
                <h3 className="text-lg font-medium text-[#111111]">
                  Select a country
                </h3>
                <button
                  onClick={() => setShowCountryModal(false)}
                  className="p-2 bg-[#f3f4f6] hover:bg-[#e5e7eb] rounded-full text-gray-500 transition-colors cursor-pointer border-none"
                >
                  <X size={20} />
                </button>
              </div>

              <div className="relative">
                <Search
                  size={20}
                  className="absolute left-4 top-1/2 -translate-y-1/2 text-gray-400"
                />
                <input
                  type="text"
                  placeholder="Search..."
                  value={countrySearch}
                  onChange={(e) => setCountrySearch(e.target.value)}
                  className="w-full bg-[#f9fafb] border-none border-b-2 border-b-[#4f46e5] pl-12 pr-4 py-3 text-[#111111] placeholder-[#9ca3af] text-base outline-none rounded-t-lg"
                />
              </div>
            </div>

            <div className="flex-1 overflow-y-auto p-2 min-h-0">
              {filteredCountries.map((c) => (
                <button
                  key={c.code}
                  onClick={() => {
                    setFormData({ ...formData, country: c });
                    setShowCountryModal(false);
                    setCountrySearch("");
                  }}
                  className="w-full flex items-center gap-4 px-4 py-3 hover:bg-[#f3f4f6] rounded-xl transition-colors text-left cursor-pointer border-none bg-transparent"
                >
                  <img
                    src={c.flag}
                    alt={c.name}
                    className="w-7 h-5 object-cover rounded shadow-sm bg-gray-100 shrink-0"
                  />
                  <span className="text-base text-[#111111]">
                    {c.name}{" "}
                    <span className="text-[#6b7280] ml-1">({c.code})</span>
                  </span>
                  {formData.country.code === c.code && (
                    <Check size={20} className="ml-auto text-[#4f46e5]" />
                  )}
                </button>
              ))}

              {filteredCountries.length === 0 && (
                <div className="p-8 text-center text-[#6b7280]">
                  No countries found.
                </div>
              )}
            </div>
          </div>
        </div>
      )}

      {/* 3. Add Member Modal */}
      {showAddMemberModal && (
        <div className="fixed inset-0 z-[200] flex items-end justify-center sm:items-center bg-black/40 transition-opacity">
          <div
            className="absolute inset-0"
            onClick={closeAddMemberModal}
          />
          <div className="relative bg-white w-full sm:max-w-[420px] rounded-t-[32px] sm:rounded-3xl p-6 animate-in slide-in-from-bottom-10 sm:slide-in-from-bottom-0 sm:fade-in duration-200 shadow-xl">
            <div className="flex items-center justify-between mb-5">
              <h3 className="text-lg font-medium text-[#111111]">
                Add Receptionist
              </h3>
              <button
                onClick={closeAddMemberModal}
                className="p-2 bg-[#f3f4f6] hover:bg-[#e5e7eb] rounded-full text-gray-500 transition-colors cursor-pointer border-none"
              >
                <X size={20} />
              </button>
            </div>

            {inviteSuccess ? (
              <div className="flex flex-col items-center py-6 gap-3">
                <div className="w-14 h-14 rounded-full bg-[#d1fae5] flex items-center justify-center text-[#10b981]">
                  <Check size={28} />
                </div>
                <p className="text-[15px] font-medium text-[#111111]">
                  Invitation sent successfully!
                </p>
              </div>
            ) : (
              <>
                <p className="text-sm text-[#6b7280] mb-4">
                  Enter the email address to invite a receptionist to this
                  hospital.
                </p>

                <CustomInput
                  icon={<Mail size={18} />}
                  label="Email address"
                  value={inviteEmail}
                  onChange={(e) => {
                    setInviteEmail(e.target.value);
                    setInviteError(null);
                  }}
                  iconColor="text-[#4f46e5]"
                />

                {inviteError && (
                  <p className="text-sm text-red-500 mt-2">{inviteError}</p>
                )}

                <button
                  onClick={handleInviteMember}
                  disabled={inviteLoading}
                  className="w-full mt-5 bg-[#4f46e5] hover:bg-[#4338ca] disabled:opacity-50 text-white py-3.5 rounded-2xl font-medium text-base transition-colors shadow-md border-none cursor-pointer"
                >
                  {inviteLoading ? "Sending invite..." : "Send Invite"}
                </button>
              </>
            )}
          </div>
        </div>
      )}
    </div>
  );
}

function SectionHeading({
  icon,
  iconColorClass,
  iconBgClass,
  title,
  noMargin = false,
}: {
  icon: React.ReactNode;
  iconColorClass: string;
  iconBgClass: string;
  title: string;
  noMargin?: boolean;
}) {
  return (
    <div className={`flex items-center gap-2.5 ${noMargin ? "" : "mb-5"}`}>
      <span
        className={`w-9 h-9 rounded-lg flex items-center justify-center flex-shrink-0 ${iconBgClass} ${iconColorClass}`}
      >
        {icon}
      </span>
      <span className="text-sm font-medium text-[#4b5563]">{title}</span>
    </div>
  );
}

function InfoRow({
  icon,
  label,
  value,
  iconColor = "text-[#6366f1]",
}: {
  icon: React.ReactNode;
  label: string;
  value: string;
  iconColor?: string;
}) {
  return (
    <div className="flex items-start gap-4">
      <div className={`mt-0.5 ${iconColor}`}>{icon}</div>
      <div>
        <p className="text-xs text-[#9ca3af] font-medium mb-0.5">{label}</p>
        <p className="text-[15px] text-[#111827]">{value}</p>
      </div>
    </div>
  );
}

function CustomInput({
  icon,
  label,
  value,
  onChange,
  iconColor = "text-[#6b7280]",
}: {
  icon: React.ReactNode;
  label: string;
  value: string;
  onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
  iconColor?: string;
}) {
  return (
    <div className="flex flex-col gap-2">
      <label className="text-sm font-medium text-[#4b5563]">{label}</label>
      <div className="flex items-center gap-3 rounded-xl border border-[#e5e7eb] bg-white px-4 py-3.5 transition-colors focus-within:border-[#4f46e5]">
        <span className={`flex-shrink-0 ${iconColor}`}>{icon}</span>
        <input
          type="text"
          value={value}
          onChange={onChange}
          placeholder="Enter details..."
          className="w-full bg-transparent border-none outline-none text-base text-[#111111] placeholder:text-[#9ca3af]"
        />
      </div>
    </div>
  );
}