"use client";

import { useEffect, useState } from "react";
import {
  Settings,
  Users,
  Building2,
  Briefcase,
  Save,
  Bell,
  Shield,
  Palette,
  User,
  Smartphone,
  MessageSquare,
  Lock,
  UserCheck,
  ExternalLink,
  CheckCircle2,
  Crown,
  ChevronRight,
  Landmark,
  RefreshCw,
  Database,
  Clock3,
} from "lucide-react";

type HrisModuleSetting = {
  enabled: boolean;
  selfServicePortal: boolean;
  ptoTracking: boolean;
  benefitsAdministration: boolean;
  complianceMonitoring: boolean;
  orgChart: boolean;
  canManage: boolean;
  currentUser: { id: number; name: string; role: string } | null;
};

type SchedulingSetting = {
  enabled: boolean;
  lawEnforcementTemplates: boolean;
  overtimeTracking: boolean;
  shiftSwapRequests: boolean;
  minStaffingAlerts: boolean;
  canManage: boolean;
};

type TextMessagingSetting = {
  enabled: boolean;
  provider: "mock" | "external";
  fromNumber: string;
  consentRequired: boolean;
  canManage: boolean;
  currentUser: { id: number; name: string; role: string } | null;
};

type ThemeSetting = {
  color: string;
};

type MunisSetting = {
  enabled: boolean;
  mode: "mock" | "live";
  baseUrl: string;
  tokenUrl: string;
  clientId: string;
  clientSecret: string;
  scope: string;
  employeeEndpoint: string;
  workforceEndpoint: string;
  autoPushOnHire: boolean;
  includeCompensation: boolean;
  includeEmergencyContact: boolean;
  includeOrganization: boolean;
  lastPushAt?: string | null;
  canManage: boolean;
  hasSecret?: boolean;
};

export default function SettingsPage() {
  const [activeTab, setActiveTab] = useState("general");
  const [textingSetting, setTextingSetting] = useState<TextMessagingSetting | null>(null);
  const [textingStatus, setTextingStatus] = useState("");
  const [savingTexting, setSavingTexting] = useState(false);

  const [hrisSetting, setHrisSetting] = useState<HrisModuleSetting | null>(null);
  const [hrisStatus, setHrisStatus] = useState("");
  const [savingHris, setSavingHris] = useState(false);

  const [schedulingSetting, setSchedulingSetting] = useState<SchedulingSetting | null>(null);
  const [schedulingStatus, setSchedulingStatus] = useState("");
  const [savingScheduling, setSavingScheduling] = useState(false);

  const [themeSetting, setThemeSetting] = useState<ThemeSetting | null>(null);
  const [themeStatus, setThemeStatus] = useState("");
  const [savingTheme, setSavingTheme] = useState(false);

  const [munisSetting, setMunisSetting] = useState<MunisSetting | null>(null);
  const [munisStatus, setMunisStatus] = useState("");
  const [savingMunis, setSavingMunis] = useState(false);

  useEffect(() => {
    fetch("/api/settings/text-messaging")
      .then((res) => res.json())
      .then((data) => setTextingSetting(data))
      .catch(() => setTextingStatus("Unable to load text messaging settings."));

    fetch("/api/settings/hris")
      .then((res) => res.json())
      .then((data) => setHrisSetting(data))
      .catch(() => setHrisStatus("Unable to load HRIS module settings."));

    fetch("/api/settings/scheduling")
      .then((res) => res.json())
      .then((data) => setSchedulingSetting(data))
      .catch(() => setSchedulingStatus("Unable to load Scheduling module settings."));

    fetch("/api/settings/theme")
      .then((res) => res.json())
      .then((data) => setThemeSetting(data))
      .catch(() => setThemeStatus("Unable to load theme settings."));

    fetch("/api/settings/munis")
      .then((res) => res.json())
      .then((data) => setMunisSetting(data))
      .catch(() => setMunisStatus("Unable to load Tyler Munis settings."));
  }, []);

  async function saveThemeSetting(color: string) {
    setSavingTheme(true);
    setThemeStatus("");

    const response = await fetch("/api/settings/theme", {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ color }),
    });

    const data = await response.json();
    setSavingTheme(false);

    if (!response.ok) {
      setThemeStatus(data.error || "Unable to update theme settings.");
      return;
    }

    setThemeSetting({ color });
    setThemeStatus("Theme updated successfully.");
    window.dispatchEvent(new CustomEvent("brand_theme_updated", { detail: { color } }));
  }

  async function saveMunisSetting(next: Partial<MunisSetting>) {
    if (!munisSetting) return;
    setSavingMunis(true);
    setMunisStatus("");
    try {
      const response = await fetch("/api/settings/munis", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ ...munisSetting, ...next }),
      });
      const data = await response.json();
      if (!response.ok) {
        setMunisStatus(data.error || "Unable to update Munis settings.");
        return;
      }
      setMunisSetting(data);
      setMunisStatus(data.enabled ? "Tyler Munis integration enabled and saved." : "Tyler Munis integration disabled.");
    } catch {
      setMunisStatus("Network error updating Munis integration.");
    } finally {
      setSavingMunis(false);
    }
  }

  async function saveSchedulingSetting(nextSetting: Partial<SchedulingSetting>) {
    if (!schedulingSetting) return;
    setSavingScheduling(true);
    setSchedulingStatus("");

    const response = await fetch("/api/settings/scheduling", {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ ...schedulingSetting, ...nextSetting }),
    });

    const data = await response.json();
    setSavingScheduling(false);

    if (!response.ok) {
      setSchedulingStatus(data.error || "Unable to update Scheduling module settings.");
      return;
    }

    setSchedulingSetting(data);
    setSchedulingStatus(data.enabled ? "Scheduling Module is now enabled." : "Scheduling Module is now disabled.");
    window.dispatchEvent(new Event("scheduling_setting_updated"));
  }

  async function saveHrisSetting(nextSetting: Partial<HrisModuleSetting>) {
    if (!hrisSetting) return;
    setSavingHris(true);
    setHrisStatus("");

    const response = await fetch("/api/settings/hris", {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ ...hrisSetting, ...nextSetting }),
    });

    const data = await response.json();
    setSavingHris(false);

    if (!response.ok) {
      setHrisStatus(data.error || "Unable to update HRIS module settings.");
      return;
    }

    setHrisSetting(data);
    setHrisStatus(data.enabled ? "HRIS Module is now enabled for your organization." : "HRIS Module is now disabled.");
    window.dispatchEvent(new Event("hris_setting_updated"));
  }

  async function saveTextingSetting(nextSetting: Partial<TextMessagingSetting>) {
    if (!textingSetting) return;
    setSavingTexting(true);
    setTextingStatus("");

    const response = await fetch("/api/settings/text-messaging", {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ ...textingSetting, ...nextSetting }),
    });

    const data = await response.json();
    setSavingTexting(false);

    if (!response.ok) {
      setTextingStatus(data.error || "Unable to update text messaging settings.");
      return;
    }

    setTextingSetting(data);
    setTextingStatus(data.enabled ? "Candidate texting is now enabled." : "Candidate texting is now disabled.");
  }

  const tabs = [
    { id: "general", label: "General", icon: Settings },
    { id: "appearance", label: "Appearance", icon: Palette },
    { id: "team", label: "Team", icon: Users },
    { id: "departments", label: "Departments", icon: Building2 },
    { id: "texting", label: "Text Messaging", icon: Smartphone },
    { id: "hris", label: "HRIS Module", icon: UserCheck },
    { id: "scheduling", label: "Scheduling", icon: Clock3 },
    { id: "integrations", label: "Integrations", icon: Landmark },
    { id: "clients", label: "Client Accounts", icon: Building2 },
    { id: "notifications", label: "Notifications", icon: Bell },
    { id: "security", label: "Security", icon: Shield },
  ];

  const teamMembers = [
    { name: "Sarah Johnson", email: "sarah@company.com", role: "Admin", avatar: "SJ" },
    { name: "Mike Chen", email: "mike@company.com", role: "Recruiter", avatar: "MC" },
    { name: "Emily Davis", email: "emily@company.com", role: "Hiring Manager", avatar: "ED" },
    { name: "Alex Thompson", email: "alex@company.com", role: "Recruiter", avatar: "AT" },
  ];

  const departments = [
    { name: "Engineering", description: "Software development and engineering teams", jobs: 2 },
    { name: "Design", description: "Product design and UX research", jobs: 1 },
    { name: "Marketing", description: "Marketing and growth", jobs: 1 },
    { name: "Sales", description: "Sales and business development", jobs: 1 },
  ];

  return (
    <div className="p-6">
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-gray-900">Settings</h1>
        <p className="text-gray-500 mt-1">Manage your recruitment workspace</p>
      </div>

      <div className="flex gap-6">
        {/* Sidebar Tabs */}
        <div className="w-56 shrink-0">
          <div className="bg-white rounded-xl border border-gray-200 shadow-sm overflow-hidden">
            {tabs.map((tab) => {
              const Icon = tab.icon;
              return (
                <button
                  key={tab.id}
                  onClick={() => setActiveTab(tab.id)}
                  className={`w-full flex items-center gap-3 px-4 py-3 text-sm transition-colors ${
                    activeTab === tab.id
                      ? "bg-blue-50 text-blue-700 font-medium border-r-2 border-blue-600"
                      : "text-gray-600 hover:bg-gray-50"
                  }`}
                >
                  <Icon className="w-4 h-4" />
                  {tab.label}
                </button>
              );
            })}
          </div>
        </div>

        {/* Content */}
        <div className="flex-1 bg-white rounded-xl border border-gray-200 shadow-sm p-6">
          {activeTab === "appearance" && (
            <div>
              <h2 className="text-lg font-semibold text-gray-900 mb-6">Brand Theme</h2>
              <div className="space-y-4 max-w-lg">
                <p className="text-sm text-gray-500">
                  Select a primary color theme for your workspace. This updates buttons, links, and highlights across the entire application instantly.
                </p>
                
                <div className="grid grid-cols-2 sm:grid-cols-4 gap-4 mt-4">
                  {[
                    { key: "blue", label: "Blue", bgClass: "bg-blue-600" },
                    { key: "indigo", label: "Indigo", bgClass: "bg-indigo-600" },
                    { key: "emerald", label: "Emerald", bgClass: "bg-emerald-600" },
                    { key: "teal", label: "Teal", bgClass: "bg-teal-600" },
                    { key: "violet", label: "Violet", bgClass: "bg-violet-600" },
                    { key: "rose", label: "Rose", bgClass: "bg-rose-600" },
                    { key: "slate", label: "Slate", bgClass: "bg-slate-700" },
                  ].map((colorOption) => (
                    <button
                      key={colorOption.key}
                      disabled={savingTheme}
                      onClick={() => saveThemeSetting(colorOption.key)}
                      className={`flex flex-col items-center gap-2 p-3 rounded-xl border-2 transition-all ${
                        themeSetting?.color === colorOption.key
                          ? "border-gray-900 bg-gray-50 shadow-sm scale-105"
                          : "border-transparent hover:bg-gray-50 hover:scale-105"
                      }`}
                    >
                      <div className={`w-10 h-10 rounded-full shadow-inner ${colorOption.bgClass} flex items-center justify-center`}>
                        {themeSetting?.color === colorOption.key && (
                          <CheckCircle2 className="w-5 h-5 text-white" />
                        )}
                      </div>
                      <span className="text-sm font-medium text-gray-700">{colorOption.label}</span>
                    </button>
                  ))}
                </div>

                {themeStatus && (
                  <p className={`text-sm mt-4 ${themeStatus.includes("Unable") || themeStatus.includes("Only") ? "text-red-600" : "text-green-600"}`}>
                    {themeStatus}
                  </p>
                )}
              </div>
            </div>
          )}

          {activeTab === "general" && (
            <div>
              <h2 className="text-lg font-semibold text-gray-900 mb-6">General Settings</h2>
              <div className="space-y-4 max-w-lg">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Company Name</label>
                  <input
                    type="text"
                    defaultValue="Acme Corp"
                    className="w-full px-3 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Company Website</label>
                  <input
                    type="text"
                    defaultValue="https://acmecorp.com"
                    className="w-full px-3 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Default Job Location</label>
                  <input
                    type="text"
                    defaultValue="Remote"
                    className="w-full px-3 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Time Zone</label>
                  <select className="w-full px-3 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm">
                    <option>Pacific Time (PT)</option>
                    <option>Mountain Time (MT)</option>
                    <option>Central Time (CT)</option>
                    <option>Eastern Time (ET)</option>
                  </select>
                </div>
                <div className="pt-4">
                  <button className="flex items-center gap-2 bg-blue-600 text-white px-4 py-2.5 rounded-lg hover:bg-blue-700 transition-colors text-sm font-medium">
                    <Save className="w-4 h-4" />
                    Save Changes
                  </button>
                </div>
              </div>
            </div>
          )}

          {activeTab === "team" && (
            <div>
              <div className="flex items-center justify-between mb-6">
                <h2 className="text-lg font-semibold text-gray-900">Team Members</h2>
                <button className="flex items-center gap-2 bg-blue-600 text-white px-3 py-2 rounded-lg hover:bg-blue-700 transition-colors text-sm font-medium">
                  <Users className="w-4 h-4" />
                  Invite Member
                </button>
              </div>
              <div className="space-y-3">
                {teamMembers.map((member) => (
                  <div
                    key={member.email}
                    className="flex items-center justify-between p-4 bg-gray-50 rounded-lg"
                  >
                    <div className="flex items-center gap-3">
                      <div className="w-10 h-10 bg-blue-100 rounded-full flex items-center justify-center text-sm font-medium text-blue-700">
                        {member.avatar}
                      </div>
                      <div>
                        <p className="text-sm font-medium text-gray-900">{member.name}</p>
                        <p className="text-xs text-gray-500">{member.email}</p>
                      </div>
                    </div>
                    <div className="flex items-center gap-3">
                      <select
                        defaultValue={member.role}
                        className="px-2 py-1.5 border border-gray-300 rounded-lg text-sm"
                      >
                        <option>Admin</option>
                        <option>Recruiter</option>
                        <option>Hiring Manager</option>
                        <option>Interviewer</option>
                      </select>
                      <button className="text-sm text-red-600 hover:text-red-700">Remove</button>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {activeTab === "departments" && (
            <div>
              <div className="flex items-center justify-between mb-6">
                <h2 className="text-lg font-semibold text-gray-900">Departments</h2>
                <button className="flex items-center gap-2 bg-blue-600 text-white px-3 py-2 rounded-lg hover:bg-blue-700 transition-colors text-sm font-medium">
                  <Building2 className="w-4 h-4" />
                  Add Department
                </button>
              </div>
              <div className="space-y-3">
                {departments.map((dept) => (
                  <div
                    key={dept.name}
                    className="flex items-center justify-between p-4 bg-gray-50 rounded-lg"
                  >
                    <div>
                      <p className="text-sm font-medium text-gray-900">{dept.name}</p>
                      <p className="text-xs text-gray-500">{dept.description}</p>
                    </div>
                    <div className="flex items-center gap-3">
                      <span className="text-sm text-gray-500">{dept.jobs} open jobs</span>
                      <button className="text-sm text-red-600 hover:text-red-700">Delete</button>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {activeTab === "texting" && (
            <div>
              <div className="flex items-start justify-between mb-6">
                <div>
                  <h2 className="text-lg font-semibold text-gray-900">Text Messaging</h2>
                  <p className="text-sm text-gray-500 mt-1">
                    Super users can turn candidate SMS messaging on or off for the whole workspace.
                  </p>
                </div>
                <span
                  className={`text-xs px-2.5 py-1 rounded-full font-medium ${
                    textingSetting?.enabled ? "bg-green-100 text-green-700" : "bg-gray-100 text-gray-600"
                  }`}
                >
                  {textingSetting?.enabled ? "Enabled" : "Disabled"}
                </span>
              </div>

              {!textingSetting ? (
                <div className="flex items-center gap-3 p-4 bg-gray-50 rounded-lg text-sm text-gray-500">
                  <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600" />
                  Loading text messaging settings...
                </div>
              ) : (
                <div className="space-y-5 max-w-2xl">
                  <div className="p-4 bg-blue-50 border border-blue-100 rounded-xl">
                    <div className="flex items-start gap-3">
                      <MessageSquare className="w-5 h-5 text-blue-600 mt-0.5" />
                      <div>
                        <p className="text-sm font-medium text-blue-900">Candidate texting workflow</p>
                        <p className="text-sm text-blue-700 mt-1">
                          When enabled, recruiters can send logged text messages from candidate profiles.
                          This clone uses a mock SMS provider by default and stores every outbound message
                          in the database for auditability.
                        </p>
                      </div>
                    </div>
                  </div>

                  {!textingSetting.canManage && (
                    <div className="p-4 bg-amber-50 border border-amber-200 rounded-xl flex items-start gap-3">
                      <Lock className="w-5 h-5 text-amber-600 mt-0.5" />
                      <div>
                        <p className="text-sm font-medium text-amber-800">Super user access required</p>
                        <p className="text-sm text-amber-700 mt-1">
                          You can view this setting, but only a super user can turn candidate texting on or off.
                        </p>
                      </div>
                    </div>
                  )}

                  <div className="flex items-center justify-between p-4 bg-gray-50 rounded-xl">
                    <div>
                      <p className="text-sm font-medium text-gray-900">Allow texting candidates</p>
                      <p className="text-xs text-gray-500 mt-0.5">
                        Enables the SMS action on candidate profiles for candidates with phone numbers.
                      </p>
                    </div>
                    <label className="relative inline-flex items-center cursor-pointer">
                      <input
                        type="checkbox"
                        checked={textingSetting.enabled}
                        disabled={!textingSetting.canManage || savingTexting}
                        onChange={(event) => saveTextingSetting({ enabled: event.target.checked })}
                        className="sr-only peer"
                      />
                      <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-blue-300 rounded-full peer disabled:opacity-50 peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
                    </label>
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">Sender Number</label>
                    <input
                      type="text"
                      value={textingSetting.fromNumber}
                      disabled={!textingSetting.canManage || savingTexting}
                      onChange={(event) =>
                        setTextingSetting({ ...textingSetting, fromNumber: event.target.value })
                      }
                      className="w-full px-3 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm disabled:bg-gray-50 disabled:text-gray-400"
                    />
                    <p className="text-xs text-gray-500 mt-1">
                      This is displayed as the configured sender number. Use SMS_FROM_NUMBER for server defaults.
                    </p>
                  </div>

                  <div className="flex items-center justify-between p-4 bg-gray-50 rounded-xl">
                    <div>
                      <p className="text-sm font-medium text-gray-900">Require candidate consent</p>
                      <p className="text-xs text-gray-500 mt-0.5">
                        Keeps compliance messaging visible before recruiters send SMS.
                      </p>
                    </div>
                    <label className="relative inline-flex items-center cursor-pointer">
                      <input
                        type="checkbox"
                        checked={textingSetting.consentRequired}
                        disabled={!textingSetting.canManage || savingTexting}
                        onChange={(event) =>
                          saveTextingSetting({ consentRequired: event.target.checked })
                        }
                        className="sr-only peer"
                      />
                      <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
                    </label>
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">Provider Mode</label>
                    <select
                      value={textingSetting.provider}
                      disabled={!textingSetting.canManage || savingTexting}
                      onChange={(event) =>
                        saveTextingSetting({ provider: event.target.value as "mock" | "external" })
                      }
                      className="w-full px-3 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm disabled:bg-gray-50 disabled:text-gray-400"
                    >
                      <option value="mock">Mock provider (log-only demo)</option>
                      <option value="external">External provider-ready</option>
                    </select>
                  </div>

                  <button
                    onClick={() => saveTextingSetting({ fromNumber: textingSetting.fromNumber })}
                    disabled={!textingSetting.canManage || savingTexting}
                    className="flex items-center gap-2 bg-blue-600 text-white px-4 py-2.5 rounded-lg hover:bg-blue-700 transition-colors text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    <Save className="w-4 h-4" />
                    {savingTexting ? "Saving..." : "Save Texting Settings"}
                  </button>

                  {textingStatus && (
                    <p
                      className={`text-sm ${
                        textingStatus.includes("Unable") || textingStatus.includes("Only")
                          ? "text-red-600"
                          : "text-green-600"
                      }`}
                    >
                      {textingStatus}
                    </p>
                  )}
                </div>
              )}
            </div>
          )}

          {activeTab === "hris" && (
            <div>
              <div className="flex items-start justify-between mb-6">
                <div>
                  <h2 className="text-lg font-semibold text-gray-900">HRIS Workforce Module</h2>
                  <p className="text-sm text-gray-500 mt-1">
                    Super administrators can opt into and configure the Human Resources Information System for employee management, time off, and benefits.
                  </p>
                </div>
                <span
                  className={`text-xs px-2.5 py-1 rounded-full font-medium ${
                    hrisSetting?.enabled ? "bg-green-100 text-green-700" : "bg-gray-100 text-gray-600"
                  }`}
                >
                  {hrisSetting?.enabled ? "Opted In (Active)" : "Opted Out (Disabled)"}
                </span>
              </div>

              {!hrisSetting ? (
                <div className="flex items-center gap-3 p-4 bg-gray-50 rounded-lg text-sm text-gray-500">
                  <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600" />
                  Loading HRIS module settings...
                </div>
              ) : (
                <div className="space-y-5 max-w-2xl">
                  <div className="p-4 bg-indigo-50 border border-indigo-100 rounded-xl">
                    <div className="flex items-start gap-3">
                      <UserCheck className="w-5 h-5 text-indigo-600 mt-0.5" />
                      <div>
                        <p className="text-sm font-medium text-indigo-900">Unified Recruitment to Workforce Management</p>
                        <p className="text-sm text-indigo-700 mt-1">
                          When opted in, your organization gets access to the full HRIS workspace (`/hris`). You can seamlessly convert completed onboarding hires into permanent employee records, manage paid time off (PTO) requests, and administer employer benefit packages.
                        </p>
                      </div>
                    </div>
                  </div>

                  {!hrisSetting.canManage && (
                    <div className="p-4 bg-amber-50 border border-amber-200 rounded-xl flex items-start gap-3">
                      <Lock className="w-5 h-5 text-amber-600 mt-0.5" />
                      <div>
                        <p className="text-sm font-medium text-amber-800">Super user access required</p>
                        <p className="text-sm text-amber-700 mt-1">
                          Only a Super Administrator can opt the organization into or out of the HRIS suite.
                        </p>
                      </div>
                    </div>
                  )}

                  <div className="flex items-center justify-between p-4 bg-gray-50 rounded-xl border border-gray-200/80">
                    <div>
                      <p className="text-sm font-medium text-gray-900">Enable HRIS Module (Company Opt-In)</p>
                      <p className="text-xs text-gray-500 mt-0.5">
                        Turns on the HRIS navigation section and unlocks employee directory, PTO, and benefits management.
                      </p>
                    </div>
                    <label className="relative inline-flex items-center cursor-pointer">
                      <input
                        type="checkbox"
                        checked={hrisSetting.enabled}
                        disabled={!hrisSetting.canManage || savingHris}
                        onChange={(event) => saveHrisSetting({ enabled: event.target.checked })}
                        className="sr-only peer"
                      />
                      <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-indigo-300 rounded-full peer disabled:opacity-50 peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-indigo-600"></div>
                    </label>
                  </div>

                  {hrisSetting.enabled && (
                    <>
                      <div className="flex items-center justify-between p-4 bg-gray-50 rounded-xl">
                        <div>
                          <p className="text-sm font-medium text-gray-900">Self-Service Employee Portal</p>
                          <p className="text-xs text-gray-500 mt-0.5">Allow employees to view their compensation and emergency details.</p>
                        </div>
                        <label className="relative inline-flex items-center cursor-pointer">
                          <input
                            type="checkbox"
                            checked={hrisSetting.selfServicePortal}
                            disabled={!hrisSetting.canManage || savingHris}
                            onChange={(event) => saveHrisSetting({ selfServicePortal: event.target.checked })}
                            className="sr-only peer"
                          />
                          <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-indigo-300 rounded-full peer peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-indigo-600"></div>
                        </label>
                      </div>

                      <div className="flex items-center justify-between p-4 bg-gray-50 rounded-xl">
                        <div>
                          <p className="text-sm font-medium text-gray-900">Paid Time Off (PTO) & Leave Tracking</p>
                          <p className="text-xs text-gray-500 mt-0.5">Enable time-off balance deductions and manager approval workflows.</p>
                        </div>
                        <label className="relative inline-flex items-center cursor-pointer">
                          <input
                            type="checkbox"
                            checked={hrisSetting.ptoTracking}
                            disabled={!hrisSetting.canManage || savingHris}
                            onChange={(event) => saveHrisSetting({ ptoTracking: event.target.checked })}
                            className="sr-only peer"
                          />
                          <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-indigo-300 rounded-full peer peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-indigo-600"></div>
                        </label>
                      </div>

                      <div className="flex items-center justify-between p-4 bg-gray-50 rounded-xl">
                        <div>
                          <p className="text-sm font-medium text-gray-900">Benefits & Payroll Administration</p>
                          <p className="text-xs text-gray-500 mt-0.5">Manage health, dental, and retirement plan enrollments.</p>
                        </div>
                        <label className="relative inline-flex items-center cursor-pointer">
                          <input
                            type="checkbox"
                            checked={hrisSetting.benefitsAdministration}
                            disabled={!hrisSetting.canManage || savingHris}
                            onChange={(event) => saveHrisSetting({ benefitsAdministration: event.target.checked })}
                            className="sr-only peer"
                          />
                          <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-indigo-300 rounded-full peer peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-indigo-600"></div>
                        </label>
                      </div>

                      <div className="flex items-center justify-between p-4 bg-indigo-50 border border-indigo-100 rounded-xl">
                        <div>
                          <p className="text-sm font-semibold text-indigo-900">Organizational Chart</p>
                          <p className="text-xs text-indigo-700 mt-0.5">Publish an interactive reporting hierarchy sourced live from the HRIS directory.</p>
                        </div>
                        <label className="relative inline-flex items-center cursor-pointer">
                          <input
                            type="checkbox"
                            checked={hrisSetting.orgChart}
                            disabled={!hrisSetting.canManage || savingHris}
                            onChange={(event) => saveHrisSetting({ orgChart: event.target.checked })}
                            className="sr-only peer"
                          />
                          <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-indigo-300 rounded-full peer peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-indigo-600"></div>
                        </label>
                      </div>

                      <div className="pt-2 flex flex-wrap gap-2">
                        <a
                          href="/hris"
                          className="inline-flex items-center gap-2 px-5 py-2.5 bg-indigo-600 text-white rounded-xl hover:bg-indigo-700 transition-colors text-sm font-semibold shadow-sm"
                        >
                          <span>Launch HRIS Workforce Hub</span>
                          <ExternalLink className="w-4 h-4" />
                        </a>
                        {hrisSetting.orgChart && (
                          <a
                            href="/hris/org-chart"
                            className="inline-flex items-center gap-2 px-5 py-2.5 bg-white border border-indigo-200 text-indigo-700 rounded-xl hover:bg-indigo-50 transition-colors text-sm font-semibold"
                          >
                            <span>Open Org Chart</span>
                            <ExternalLink className="w-4 h-4" />
                          </a>
                        )}
                      </div>
                    </>
                  )}

                  {hrisStatus && (
                    <p
                      className={`text-sm ${
                        hrisStatus.includes("Unable") || hrisStatus.includes("Only")
                          ? "text-red-600"
                          : "text-green-600"
                      }`}
                    >
                      {hrisStatus}
                    </p>
                  )}
                </div>
              )}
            </div>
          )}

          {activeTab === "notifications" && (
            <div>
              <h2 className="text-lg font-semibold text-gray-900 mb-6">Notification Preferences</h2>
              <div className="space-y-4 max-w-lg">
                {[
                  { label: "New application notifications", desc: "Get notified when a new candidate applies", defaultChecked: true },
                  { label: "Interview reminders", desc: "Receive reminders 1 hour before scheduled interviews", defaultChecked: true },
                  { label: "Stage change notifications", desc: "Get notified when candidates move between stages", defaultChecked: false },
                  { label: "Evaluation requests", desc: "Get notified when you are asked to evaluate a candidate", defaultChecked: true },
                  { label: "Weekly summary report", desc: "Receive a weekly recruitment summary every Monday", defaultChecked: true },
                ].map((item, i) => (
                  <div key={i} className="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
                    <div>
                      <p className="text-sm font-medium text-gray-900">{item.label}</p>
                      <p className="text-xs text-gray-500">{item.desc}</p>
                    </div>
                    <label className="relative inline-flex items-center cursor-pointer">
                      <input
                        type="checkbox"
                        defaultChecked={item.defaultChecked}
                        className="sr-only peer"
                      />
                      <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
                    </label>
                  </div>
                ))}
              </div>
            </div>
          )}

          {activeTab === "scheduling" && (
            <div>
              <div className="flex items-start justify-between mb-6">
                <div>
                  <h2 className="text-lg font-semibold text-gray-900">Scheduling Module</h2>
                  <p className="text-sm text-gray-500 mt-1">Enable workforce schedules, public-safety rotations, Pitman schedules, shift swaps and staffing alerts.</p>
                </div>
                <span className={`text-xs px-2.5 py-1 rounded-full font-bold ${schedulingSetting?.enabled ? "bg-emerald-100 text-emerald-700" : "bg-gray-100 text-gray-600"}`}>
                  {schedulingSetting?.enabled ? "Enabled" : "Disabled"}
                </span>
              </div>

              {!schedulingSetting ? (
                <div className="flex items-center gap-3 p-4 bg-gray-50 rounded-lg text-sm text-gray-500">
                  <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600" /> Loading Scheduling module settings...
                </div>
              ) : (
                <div className="space-y-5 max-w-2xl">
                  <div className="p-5 bg-blue-50 border border-blue-100 rounded-2xl">
                    <div className="flex items-start gap-3">
                      <Clock3 className="w-6 h-6 text-blue-700 mt-0.5" />
                      <div>
                        <p className="text-sm font-bold text-blue-950">All Schedule Types + Law Enforcement</p>
                        <p className="text-sm text-blue-800 mt-1 leading-relaxed">Supports standard business schedules, compressed work weeks, 12-hour rotating schedules, and law-enforcement Pitman 2-2-3 rotations.</p>
                      </div>
                    </div>
                  </div>

                  <div className="flex items-center justify-between p-4 bg-gray-50 border border-gray-200 rounded-xl">
                    <div>
                      <p className="text-sm font-semibold text-gray-900">Enable Scheduling Module</p>
                      <p className="text-xs text-gray-500 mt-0.5">Adds Scheduling to the left menu and unlocks assignment tools.</p>
                    </div>
                    <label className="relative inline-flex items-center cursor-pointer">
                      <input type="checkbox" checked={schedulingSetting.enabled} disabled={!schedulingSetting.canManage || savingScheduling} onChange={(e) => saveSchedulingSetting({ enabled: e.target.checked })} className="sr-only peer" />
                      <div className="w-11 h-6 bg-gray-200 peer-focus:ring-2 peer-focus:ring-blue-300 rounded-full peer disabled:opacity-50 peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
                    </label>
                  </div>

                  {schedulingSetting.enabled && (
                    <div className="space-y-2">
                      {[
                        { key: "lawEnforcementTemplates", label: "Law Enforcement Templates", desc: "Pitman 2-2-3 day/night patterns and public safety units." },
                        { key: "overtimeTracking", label: "Overtime Tracking", desc: "Track extra shifts, court time, training and overtime events." },
                        { key: "shiftSwapRequests", label: "Shift Swap Requests", desc: "Allow employee swap requests and manager approvals." },
                        { key: "minStaffingAlerts", label: "Minimum Staffing Alerts", desc: "Monitor coverage rules and minimum staffing thresholds." },
                      ].map((option) => (
                        <label key={option.key} className="flex items-center justify-between p-3.5 bg-gray-50 border border-gray-200 rounded-xl cursor-pointer">
                          <div>
                            <p className="text-sm font-semibold text-gray-800">{option.label}</p>
                            <p className="text-xs text-gray-500">{option.desc}</p>
                          </div>
                          <input type="checkbox" checked={Boolean(schedulingSetting[option.key as keyof SchedulingSetting])} disabled={!schedulingSetting.canManage || savingScheduling} onChange={(e) => saveSchedulingSetting({ [option.key]: e.target.checked } as Partial<SchedulingSetting>)} className="w-4 h-4 rounded border-gray-300" />
                        </label>
                      ))}
                      <a href="/scheduling" className="inline-flex items-center gap-2 mt-3 px-5 py-2.5 bg-blue-600 text-white rounded-xl hover:bg-blue-700 transition-colors text-sm font-bold shadow-sm">
                        Open Scheduling <ExternalLink className="w-4 h-4" />
                      </a>
                    </div>
                  )}

                  {schedulingStatus && <p className={`text-sm ${schedulingStatus.includes("Unable") || schedulingStatus.includes("Only") ? "text-red-600" : "text-emerald-600"}`}>{schedulingStatus}</p>}
                </div>
              )}
            </div>
          )}

          {activeTab === "integrations" && (
            <div>
              <div className="flex items-start justify-between mb-6">
                <div>
                  <h2 className="text-lg font-semibold text-gray-900">External Integrations</h2>
                  <p className="text-sm text-gray-500 mt-1">Connect H.R. Vista with third-party municipal and payroll systems.</p>
                </div>
                <span className={`text-xs px-2.5 py-1 rounded-full font-bold ${munisSetting?.enabled ? "bg-emerald-100 text-emerald-700" : "bg-gray-100 text-gray-600"}`}>
                  {munisSetting?.enabled ? "Munis Connected" : "Munis Not Connected"}
                </span>
              </div>

              {!munisSetting ? (
                <div className="flex items-center gap-3 p-4 bg-gray-50 rounded-lg text-sm text-gray-500">
                  <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-indigo-600" /> Loading integration settings...
                </div>
              ) : (
                <div className="space-y-5 max-w-2xl">
                  <div className="p-5 bg-gradient-to-br from-sky-50 to-blue-50 border border-sky-100 rounded-2xl">
                    <div className="flex items-start gap-3">
                      <Landmark className="w-6 h-6 text-sky-700 mt-0.5" />
                      <div>
                        <p className="text-sm font-bold text-sky-950">Tyler Technologies Munis</p>
                        <p className="text-sm text-sky-800 mt-1 leading-relaxed">
                          Push approved HRIS employee data, organizational assignments, compensation, and emergency contacts from H.R. Vista into Tyler Munis. The connector supports Tyler Open API OAuth client credentials and a safe demo mode.
                        </p>
                      </div>
                    </div>
                  </div>

                  {!munisSetting.canManage && (
                    <div className="p-4 bg-amber-50 border border-amber-200 rounded-xl flex items-start gap-3">
                      <Lock className="w-5 h-5 text-amber-600 mt-0.5" />
                      <p className="text-sm text-amber-800">Only super administrators and administrators can configure the Munis connection.</p>
                    </div>
                  )}

                  <div className="flex items-center justify-between p-4 bg-gray-50 border border-gray-200 rounded-xl">
                    <div>
                      <p className="text-sm font-semibold text-gray-900">Enable Tyler Munis push integration</p>
                      <p className="text-xs text-gray-500 mt-0.5">Allows authorized HR staff to push employee data from HRIS.</p>
                    </div>
                    <label className="relative inline-flex items-center cursor-pointer">
                      <input type="checkbox" checked={munisSetting.enabled} disabled={!munisSetting.canManage || savingMunis} onChange={(e) => saveMunisSetting({ enabled: e.target.checked })} className="sr-only peer" />
                      <div className="w-11 h-6 bg-gray-200 peer-focus:ring-2 peer-focus:ring-sky-300 rounded-full peer disabled:opacity-50 peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-sky-600"></div>
                    </label>
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">Connection Mode</label>
                    <select value={munisSetting.mode} disabled={!munisSetting.canManage || savingMunis} onChange={(e) => saveMunisSetting({ mode: e.target.value as "mock" | "live" })} className="w-full px-3 py-2.5 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-sky-500 focus:outline-none disabled:bg-gray-50">
                      <option value="mock">Demo Munis (safe mock push)</option>
                      <option value="live">Live Tyler Munis Open API</option>
                    </select>
                    <p className="text-xs text-gray-500 mt-1">Use Demo mode to validate employee payloads without transmitting data to a live system.</p>
                  </div>

                  {munisSetting.mode === "live" && (
                    <div className="p-4 bg-gray-50 border border-gray-200 rounded-xl space-y-4">
                      <p className="text-sm font-bold text-gray-800">Munis Open API Credentials</p>
                      <div>
                        <label className="block text-xs font-bold text-gray-500 uppercase mb-1">Munis Base URL</label>
                        <input value={munisSetting.baseUrl} disabled={!munisSetting.canManage || savingMunis} onChange={(e) => setMunisSetting({ ...munisSetting, baseUrl: e.target.value })} onBlur={() => saveMunisSetting({ baseUrl: munisSetting.baseUrl })} placeholder="https://munis.yourcity.gov" className="w-full px-3 py-2.5 border border-gray-300 rounded-lg text-sm font-mono focus:ring-2 focus:ring-sky-500 focus:outline-none" />
                      </div>
                      <div>
                        <label className="block text-xs font-bold text-gray-500 uppercase mb-1">OAuth Token URL</label>
                        <input value={munisSetting.tokenUrl} disabled={!munisSetting.canManage || savingMunis} onChange={(e) => setMunisSetting({ ...munisSetting, tokenUrl: e.target.value })} onBlur={() => saveMunisSetting({ tokenUrl: munisSetting.tokenUrl })} placeholder="https://identity.tylertech.com/connect/token" className="w-full px-3 py-2.5 border border-gray-300 rounded-lg text-sm font-mono focus:ring-2 focus:ring-sky-500 focus:outline-none" />
                      </div>
                      <div className="grid grid-cols-2 gap-4">
                        <div>
                          <label className="block text-xs font-bold text-gray-500 uppercase mb-1">Client ID</label>
                          <input value={munisSetting.clientId} disabled={!munisSetting.canManage || savingMunis} onChange={(e) => setMunisSetting({ ...munisSetting, clientId: e.target.value })} onBlur={() => saveMunisSetting({ clientId: munisSetting.clientId })} className="w-full px-3 py-2.5 border border-gray-300 rounded-lg text-sm font-mono focus:ring-2 focus:ring-sky-500 focus:outline-none" />
                        </div>
                        <div>
                          <label className="block text-xs font-bold text-gray-500 uppercase mb-1">Client Secret</label>
                          <input type="password" value={munisSetting.clientSecret} disabled={!munisSetting.canManage || savingMunis} onChange={(e) => setMunisSetting({ ...munisSetting, clientSecret: e.target.value })} onBlur={() => saveMunisSetting({ clientSecret: munisSetting.clientSecret })} placeholder={munisSetting.hasSecret ? "•••••• (saved)" : "Client secret"} className="w-full px-3 py-2.5 border border-gray-300 rounded-lg text-sm font-mono focus:ring-2 focus:ring-sky-500 focus:outline-none" />
                        </div>
                      </div>
                      <div className="grid grid-cols-2 gap-4">
                        <div>
                          <label className="block text-xs font-bold text-gray-500 uppercase mb-1">Employee Push Endpoint</label>
                          <input value={munisSetting.employeeEndpoint} disabled={!munisSetting.canManage || savingMunis} onChange={(e) => setMunisSetting({ ...munisSetting, employeeEndpoint: e.target.value })} onBlur={() => saveMunisSetting({ employeeEndpoint: munisSetting.employeeEndpoint })} className="w-full px-3 py-2.5 border border-gray-300 rounded-lg text-sm font-mono focus:ring-2 focus:ring-sky-500 focus:outline-none" />
                        </div>
                        <div>
                          <label className="block text-xs font-bold text-gray-500 uppercase mb-1">Workforce Push Endpoint</label>
                          <input value={munisSetting.workforceEndpoint} disabled={!munisSetting.canManage || savingMunis} onChange={(e) => setMunisSetting({ ...munisSetting, workforceEndpoint: e.target.value })} onBlur={() => saveMunisSetting({ workforceEndpoint: munisSetting.workforceEndpoint })} className="w-full px-3 py-2.5 border border-gray-300 rounded-lg text-sm font-mono focus:ring-2 focus:ring-sky-500 focus:outline-none" />
                        </div>
                      </div>
                    </div>
                  )}

                  <div className="space-y-2">
                    {[
                      { key: "autoPushOnHire", label: "Push new hires automatically", desc: "Send a new employee record when an onboarding case is completed." },
                      { key: "includeCompensation", label: "Include compensation details", desc: "Map HRIS annual salary to the Munis payload." },
                      { key: "includeEmergencyContact", label: "Include emergency contact", desc: "Map employee emergency contact details to the payload." },
                      { key: "includeOrganization", label: "Include organizational hierarchy", desc: "Include department and reporting supervisor employee numbers." },
                    ].map((option) => (
                      <label key={option.key} className="flex items-center justify-between p-3.5 bg-gray-50 border border-gray-200 rounded-xl cursor-pointer">
                        <div>
                          <p className="text-sm font-semibold text-gray-800">{option.label}</p>
                          <p className="text-xs text-gray-500">{option.desc}</p>
                        </div>
                        <input type="checkbox" checked={Boolean(munisSetting[option.key as keyof MunisSetting])} disabled={!munisSetting.canManage || savingMunis} onChange={(e) => saveMunisSetting({ [option.key]: e.target.checked } as Partial<MunisSetting>)} className="w-4 h-4 rounded border-gray-300" />
                      </label>
                    ))}
                  </div>

                  <div className="p-3 bg-amber-50 border border-amber-200 rounded-xl text-xs text-amber-800 flex items-start gap-2">
                    <Database className="w-4 h-4 shrink-0 mt-0.5" />
                    <span>Actual Munis APIs, endpoint names, and enabled toolkits vary by municipality. Confirm the endpoint paths with your Tyler Technologies implementation partner before enabling Live mode.</span>
                  </div>

                  {munisStatus && <p className={`text-sm ${munisStatus.includes("Unable") || munisStatus.includes("Only") || munisStatus.includes("error") ? "text-red-600" : "text-emerald-600"}`}>{munisStatus}</p>}
                </div>
              )}
            </div>
          )}

          {activeTab === "clients" && (
            <div>
              <h2 className="text-lg font-semibold text-gray-900 mb-2">Client Account Management</h2>
              <p className="text-sm text-gray-500 mb-6">
                Provision and manage client workspaces. Toggle paid feature modules (HRIS, Texting, Org Chart, Job Boards, etc.) per client account.
              </p>
              <div className="bg-blue-50 border border-blue-100 rounded-xl p-5 mb-6 flex items-start gap-3">
                <Crown className="w-5 h-5 text-blue-600 mt-0.5 shrink-0" />
                <div>
                  <p className="text-sm font-bold text-blue-900">Super Administrator Access</p>
                  <p className="text-xs text-blue-700 mt-0.5">
                    Only super admins can provision client accounts and enable/disable paid module access. Navigate to the full client management portal to create new clients and configure their feature sets.
                  </p>
                </div>
              </div>
              <a
                href="/settings/clients"
                className="inline-flex items-center gap-2 px-5 py-2.5 bg-indigo-600 text-white rounded-xl font-bold text-sm hover:bg-indigo-700 transition-colors shadow-sm"
              >
                <Building2 className="w-4 h-4" />
                <span>Open Client Management Portal</span>
                <ChevronRight className="w-4 h-4" />
              </a>
            </div>
          )}

          {activeTab === "security" && (
            <div>
              <h2 className="text-lg font-semibold text-gray-900 mb-6">Security Settings</h2>
              <div className="space-y-4 max-w-lg">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Current Password</label>
                  <input
                    type="password"
                    className="w-full px-3 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">New Password</label>
                  <input
                    type="password"
                    className="w-full px-3 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Confirm New Password</label>
                  <input
                    type="password"
                    className="w-full px-3 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
                  />
                </div>
                <div className="pt-2">
                  <button className="bg-blue-600 text-white px-4 py-2.5 rounded-lg hover:bg-blue-700 transition-colors text-sm font-medium">
                    Update Password
                  </button>
                </div>

                <div className="mt-8 pt-6 border-t border-gray-200">
                  <h3 className="text-sm font-semibold text-gray-900 mb-3">Two-Factor Authentication</h3>
                  <div className="p-4 bg-amber-50 rounded-lg border border-amber-200">
                    <p className="text-sm text-amber-700">
                      Two-factor authentication is not enabled. We recommend enabling it for added security.
                    </p>
                    <button className="mt-2 text-sm font-medium text-amber-800 hover:text-amber-900 underline">
                      Enable 2FA
                    </button>
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
