"use client";

import Link from "next/link";
import { useEffect, useState } from "react";
import { useHospitalStore } from "../store/useHospitalStore";
import { useMasterDataStore } from "../store/masterDataStore";
import Sidebar from "@/components/modals/ui/Sidebar";
import { useRouter } from "next/navigation";
import { ChevronRight } from "lucide-react";
import { myHospitalsApi } from "../services/hospial";
import MyPracticesPage from "@/app/dashboard/settings/my-practices/page"; 

interface User {
  fullname: string;
}

const Icon = {
  Settings: () => (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="12" cy="12" r="3" />
      <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z" />
    </svg>
  ),
  Plus: () => (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
      <line x1="12" y1="5" x2="12" y2="19" />
      <line x1="5" y1="12" x2="19" y2="12" />
    </svg>
  ),
  History: () => (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <rect x="3" y="4" width="18" height="18" rx="2" />
      <line x1="16" y1="2" x2="16" y2="6" />
      <line x1="8" y1="2" x2="8" y2="6" />
      <line x1="3" y1="10" x2="21" y2="10" />
    </svg>
  ),
  Hospital: () => (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <rect x="2" y="7" width="20" height="14" rx="2" />
      <path d="M16 21V5a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16" />
    </svg>
  ),
  ChevronRight: () => (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <polyline points="9 18 15 12 9 6" />
    </svg>
  ),
  Pill: () => (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="m10.5 20.5 10-10a4.95 4.95 0 1 0-7-7l-10 10a4.95 4.95 0 1 0 7 7Z" />
      <path d="m8.5 8.5 7 7" />
    </svg>
  ),
  Users: () => (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2" />
      <circle cx="9" cy="7" r="4" />
      <path d="M23 21v-2a4 4 0 0 0-3-3.87" />
      <path d="M16 3.13a4 4 0 0 1 0 7.75" />
    </svg>
  ),
  FileCheck: () => (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z" />
      <polyline points="14 2 14 8 20 8" />
      <polyline points="9 15 11 17 15 13" />
    </svg>
  ),
  Stethoscope: () => (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M4.8 2.3A.3.3 0 1 0 5 2H4a2 2 0 0 0-2 2v5a6 6 0 0 0 6 6v0a6 6 0 0 0 6-6V4a2 2 0 0 0-2-2h-1a.2.2 0 1 0 .3.3" />
      <path d="M8 15v1a6 6 0 0 0 6 6v0a6 6 0 0 0 6-6v-4" />
      <circle cx="20" cy="10" r="2" />
    </svg>
  ),
  Prescription: () => (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M9 3H5a2 2 0 0 0-2 2v4m6-6h10a2 2 0 0 1 2 2v4M9 3v18m0 0h10a2 2 0 0 0 2-2V9M9 21H5a2 2 0 0 1-2-2V9m0 0h18" />
    </svg>
  ),
  TrendUp: () => (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <polyline points="23 6 13.5 15.5 8.5 10.5 1 18" />
      <polyline points="17 6 23 6 23 12" />
    </svg>
  ),
  Lock: () => (
    <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <rect x="3" y="11" width="18" height="11" rx="2" ry="2" />
      <path d="M7 11V7a5 5 0 0 1 10 0v4" />
    </svg>
  ),
  Star: () => (
    <svg width="13" height="13" viewBox="0 0 24 24" fill="currentColor">
      <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2" />
    </svg>
  ),
  Menu: () => (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <line x1="3" y1="6" x2="21" y2="6" />
      <line x1="3" y1="12" x2="21" y2="12" />
      <line x1="3" y1="18" x2="21" y2="18" />
    </svg>
  ),
};

const BRAND = "#d4537e";
const BRAND_LIGHT = "#fce8f0"; 

const GETTING_STARTED = [
  { label: "Set up your profile", done: true },
  { label: "Add your hospital/clinic", done: false },
  { label: "Configure prescription template", done: false },
  { label: "Write your first prescription", done: false },
];

function StatCard({
  label,
  value,
  icon,
  iconColor,
  iconBg,
}: {
  label: string;
  value: string;
  icon: React.ReactNode;
  iconColor: string;
  iconBg: string;
}) {
  return (
    <div className="bg-white border border-gray-100 rounded-2xl p-4 shadow-sm">
      <div className={`w-9 h-9 rounded-lg flex items-center justify-center mb-3 ${iconBg} ${iconColor}`}>
        {icon}
      </div>
      <div className="text-2xl font-bold text-gray-900">{value}</div>
      <div className="text-xs font-semibold text-gray-500 mt-0.5">{label}</div>
    </div>
  );
}

export default function DashboardPage() {
  // const { masterData, loading, error, fetchMasterData } = useMasterDataStore();
  const { masterData, fetchMasterData } = useMasterDataStore();
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const [showPractices, setShowPractices] = useState(false); 

  useEffect(() => {
    if (masterData?.user_preferences) {
      console.log(masterData.user_preferences.selected_template_id);
    }
  }, [masterData]);

  const router = useRouter();
  const [activeHospital, setActiveHospital] = useState<any>(null);

  useEffect(() => {
    const load = async () => {
      const response = await myHospitalsApi();
      const active =
        response.data.find((hospital: any) =>
          hospital.members?.some((member: any) => member.isDefault)
        ) || response.data[0];
      setActiveHospital(active);
    };
    load();
  }, []);

  const [user, setUser] = useState<User | null>(null);

  useEffect(() => {
    fetchMasterData();
    const savedUser = localStorage.getItem("user");
    if (savedUser) {
      try {
        setUser(JSON.parse(savedUser));
      } catch (e) {
        console.error("Failed to parse user from localStorage", e);
      }
    }
  }, []);

  // const STATS = [
  //   {
  //     label: "Total Prescriptions",
  //     value: "0",
  //     icon: <Icon.FileCheck />,
  //     iconColor: "text-[#d4537e]",
  //     iconBg: "bg-[#fce8f0]",
  //   },
  //   {
  //     label: "Saved Medicines",
  //     value: String(masterData?.medicines?.length || 0),
  //     icon: <Icon.Pill />,
  //     iconColor: "text-blue-500",
  //     iconBg: "bg-blue-50",
  //   },
  //   {
  //     label: "Active Patients",
  //     value: "0",
  //     icon: <Icon.Users />,
  //     iconColor: "text-green-600",
  //     iconBg: "bg-green-50",
  //   },
  //   {
  //     label: "Saved Diagnoses",
  //     value: String(masterData?.diagnoses?.length || 0),
  //     icon: <Icon.Stethoscope />,
  //     iconColor: "text-amber-600",
  //     iconBg: "bg-amber-50",
  //   },
  // ];
 
  const QUICK_LINKS = [
    {
      label: "Saved Medicines",
      sub: `${masterData?.medicines?.length || 0} medicines`,
      panel: "medicines",
      icon: <Icon.Pill />,
      iconColor: "text-blue-500",
      iconBg: "bg-blue-50",
    },
    {
      label: "Saved Diagnoses",
      sub: `${masterData?.diagnoses?.length || 0} diagnoses`,
      panel: "diagnoses",
      icon: <Icon.Stethoscope />,
      iconColor: "text-amber-600",
      iconBg: "bg-amber-50",
    },
    {
      label: "Prescription Settings",
      sub: "Page & template",
      panel: "prescription",
      icon: <Icon.Prescription />,
      iconColor: "text-[#d4537e]",
      iconBg: "bg-[#fce8f0]",
    },
  ];

  return (
    <div className="flex min-h-screen bg-[#f6f6f7] font-sans">
      <aside className="hidden md:block w-64 shrink-0 bg-white border-r border-[#e5e7eb] sticky top-0 h-screen">
        <Sidebar user={user} />
      </aside>

      {sidebarOpen && (
        <div className="fixed inset-0 z-50 md:hidden">
          <div className="absolute inset-0 bg-black/40" onClick={() => setSidebarOpen(false)} />
          <div className="absolute left-0 top-0 bottom-0 w-60 bg-white py-6 overflow-y-auto">
            <Sidebar user={user} onClose={() => setSidebarOpen(false)} />
          </div>
        </div>
      )}

      {showPractices && (
        <div className="fixed inset-0 z-50 flex justify-end">
          <div
            className="absolute inset-0 bg-black/40"
            onClick={() => setShowPractices(false)}
          />
          <div className="relative w-full max-w-md bg-white h-full overflow-y-auto shadow-xl">
            <MyPracticesPage
              onSelectHospital={() => setShowPractices(false)}
              onAddHospital={() => {}}
            />
          </div>
        </div>
      )}

      <div className="flex-1 flex flex-col min-w-0 bg-[#f6f6f7]">
        <header className="flex md:hidden items-center justify-between px-4 h-14 bg-white border-b border-gray-200 sticky top-0 z-20">
          <button onClick={() => setSidebarOpen(true)} className="text-gray-800 flex" aria-label="Open menu">
            <Icon.Menu />
          </button>
          <Link href="/settings" className="w-9 h-9 rounded-xl flex items-center justify-center" style={{ background: BRAND_LIGHT, color: BRAND }}>
            <Icon.Settings />
          </Link>
        </header>

        <header className="h-[72px] flex items-center justify-between px-7 bg-white border-b border-[#e5e7eb] sticky top-0 z-20">
          <button onClick={() => setSidebarOpen(true)} className="md:hidden text-[#374151] bg-transparent border-none cursor-pointer p-0" aria-label="Open menu">
            <Icon.Menu />
          </button>
          <div className="hidden md:block">
            <h1 className="text-lg font-bold text-gray-900">Dashboard</h1>
            <p className="text-xs text-gray-400 font-medium">Overview of your practice</p>
          </div>
          <Link href="/prescription" className="flex items-center gap-2 text-white text-sm font-bold px-5 py-2.5 rounded-xl transition-opacity hover:opacity-90" style={{ background: BRAND }}>
            <Icon.Plus />
            New Prescription
          </Link>
        </header>

        <main className="flex-1 px-4 py-8 md:px-8 bg-[#f6f6f7] max-w-5xl w-full mx-auto">
          <div className="mb-7">
            <h1 className="text-2xl font-bold text-gray-900">
              Good morning, {user?.fullname}
            </h1>
            <p className="text-sm text-gray-500 mt-1">
              Here's what's happening with your practice today.
            </p>
          </div>

          <div className="rounded-2xl px-6 py-5 flex items-center justify-between gap-4 mb-6" style={{ background: BRAND }}>
            <div>
              <div className="flex items-center gap-2 mb-1 text-white font-bold text-sm">
                <Icon.Star /> Upgrade to PRO
              </div>
              <p className="text-xs text-white/80">
                Unlock prescription history, multiple hospitals, and advanced templates.
              </p>
            </div>
            <button
              onClick={() => router.push("/dashboard/settings/subscription")}
              className="shrink-0 bg-white text-xs font-bold px-4 py-2 rounded-lg text-[#d4537e] border-none cursor-pointer"
            >
              Upgrade Now →
            </button>
          </div>

          {/* <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 mb-6">
            {STATS.map((stat) => (
              <StatCard key={stat.label} {...stat} />
            ))}
          </div> */}

          <div
            onClick={() => router.push("/dashboard/settings?panel=practices")}
            className="bg-white border border-gray-100 rounded-2xl p-4 flex items-center gap-3 mb-4 shadow-sm hover:border-gray-300 transition-colors cursor-pointer"
          >
            <div className="w-10 h-10 rounded-xl bg-gray-50 flex items-center justify-center text-gray-500">
              <Icon.Hospital />
            </div>
            <div className="flex-1">
              <p className="text-sm font-bold text-gray-900">
                {activeHospital?.name || "No Hospital"}
              </p>
              <p className="text-sm text-[#9ca3af]">
                {activeHospital
                  ? `${activeHospital.city}, ${activeHospital.state}`
                  : "No active clinic"}
              </p>
            </div>
            {activeHospital?.members?.some((member: any) => member.isDefault) && (
              <span className="text-[10px] font-bold text-emerald-600 bg-emerald-50 px-2.5 py-1 rounded-full border border-emerald-100">
                Default
              </span>
            )}
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
            <Link href="/prescription" className="flex items-center gap-4 bg-[#d4537e] rounded-2xl p-4 text-white shadow-md">
              <div className="w-10 h-10 rounded-xl bg-white/20 flex items-center justify-center">
                <Icon.Plus />
              </div>
              <div>
                <p className="text-base font-semibold">New Prescription</p>
                <p className="text-[11px] opacity-80">Create and print in seconds</p>
              </div>
            </Link>

            <div className="flex items-center gap-4 bg-white border border-gray-100 rounded-2xl p-4 opacity-60">
              <div className="w-10 h-10 rounded-xl bg-gray-50 flex items-center justify-center text-gray-400">
                <Icon.History />
              </div>
              <div>
                <p className="text-sm font-bold text-gray-500 flex items-center gap-2">
                  Prescription History{" "}
                  <span className="bg-amber-100 text-amber-700 text-[9px] px-1.5 py-0.5 rounded">PRO</span>
                </p>
                <p className="text-sm text-[#9ca3af]">View your previous prescriptions</p>
              </div>
            </div>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div className="bg-white border border-gray-100 rounded-2xl p-6 shadow-sm">
              <p className="text-xs font-bold uppercase tracking-widest text-[#4b5563] mb-5">
                Quick Access
              </p>
              <div className="space-y-3">
                {QUICK_LINKS.map((link) => (
                  <button
                    key={link.label}
                    onClick={() => router.push(`/dashboard/settings?panel=${link.panel}`)}
                    className="flex items-center gap-3 w-full text-left hover:bg-[#f7f7f8] rounded-xl px-2 py-1.5 transition-colors"
                  >
                    <div className={`w-8 h-8 rounded-lg flex items-center justify-center ${link.iconBg} ${link.iconColor}`}>
                      {link.icon}
                    </div>
                    <span className="text-[15px] font-semibold text-[#111111]">{link.label}</span>
                    <ChevronRight className="ml-auto text-[#9ca3af]" size={16} />
                  </button>
                ))}
              </div>
            </div>

            <div className="bg-white border border-gray-100 rounded-2xl p-5 shadow-sm">
              <p className="text-[10px] font-bold text-gray-400 uppercase tracking-wider mb-4">
                Getting Started
              </p>
              <div className="space-y-3">
                {GETTING_STARTED.map((step, i) => (
                  <div key={step.label} className="flex items-center gap-3 text-sm font-medium text-gray-600">
                    <div className={`w-6 h-6 rounded-full flex items-center justify-center text-[10px] ${step.done ? "bg-[#d4537e] text-white" : "bg-gray-100"}`}>
                      {step.done ? "✓" : i + 1}
                    </div>
                    {step.label}
                  </div>
                ))}
              </div>
            </div>
          </div>
        </main>
      </div>
    </div>
  );
}