"use client";

import React from "react";
import Link from "next/link";
import { useParams, usePathname } from "next/navigation";
import { signOut, useSession } from "next-auth/react";

// Minimal SVG Icons
const Icons = {
  Search: () => (
    <svg
      width="14"
      height="14"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <circle cx="11" cy="11" r="8" />
      <path d="m21 21-4.3-4.3" />
    </svg>
  ),
  Target: () => (
    <svg
      width="14"
      height="14"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <circle cx="12" cy="12" r="10" />
      <circle cx="12" cy="12" r="6" />
      <circle cx="12" cy="12" r="2" />
    </svg>
  ),
  MessageCircle: () => (
    <svg
      width="14"
      height="14"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z" />
    </svg>
  ),
  Kanban: () => (
    <svg
      width="14"
      height="14"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <rect x="3" y="3" width="18" height="18" rx="2" ry="2" />
      <path d="M8 7v7" />
      <path d="M12 7v4" />
      <path d="M16 7v9" />
    </svg>
  ),
  FileText: () => (
    <svg
      width="14"
      height="14"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
      <path d="M14 2v6h6" />
      <line x1="16" y1="13" x2="8" y2="13" />
      <line x1="16" y1="17" x2="8" y2="17" />
      <polyline points="10 9 9 9 8 9" />
    </svg>
  ),
  Users: () => (
    <svg
      width="14"
      height="14"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2" />
      <circle cx="9" cy="7" r="4" />
      <path d="M22 21v-2a4 4 0 0 0-3-3.87" />
      <path d="M16 3.13a4 4 0 0 1 0 7.75" />
    </svg>
  ),
  Folder: () => (
    <svg
      width="14"
      height="14"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <path d="M4 20h16a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.93a2 2 0 0 1-1.66-.9l-.82-1.2A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13c0 1.1.9 2 2 2Z" />
    </svg>
  ),
  CreditCard: () => (
    <svg
      width="14"
      height="14"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <rect x="1" y="4" width="22" height="16" rx="2" ry="2" />
      <line x1="1" y1="10" x2="23" y2="10" />
    </svg>
  ),
  TrendingDown: () => (
    <svg
      width="14"
      height="14"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <polyline points="22 17 13.5 8.5 8.5 13.5 2 7" />
      <polyline points="16 17 22 17 22 11" />
    </svg>
  ),
  Clock: () => (
    <svg
      width="14"
      height="14"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <circle cx="12" cy="12" r="10" />
      <polyline points="12 6 12 12 16 14" />
    </svg>
  ),
  Settings: () => (
    <svg
      width="14"
      height="14"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      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 0 2.83 2 2 0 0 1-2.83 0l-.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-2 2 2 2 0 0 1-2-2v-.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 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.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 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.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 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z" />
    </svg>
  ),
};

function NavItem({
  icon: Icon,
  label,
  active,
  badge,
  href,
}: {
  icon?: React.ElementType;
  label: string;
  active?: boolean;
  badge?: string;
  href: string;
  inset?: boolean;
}) {
  return (
    <Link
      href={href}
      style={{
        display: "flex",
        alignItems: "center",
        justifyContent: "space-between",
        width: "100%",
        padding: "7px 10px",
        borderRadius: 6,
        background: active ? "#f6f4f0" : "transparent",
        color: active ? "#1a1a1a" : "#6b6560",
        fontWeight: active ? 600 : 500,
        fontSize: "13px",
        transition: "background 0.15s",
        border: "none",
        cursor: "pointer",
        textDecoration: "none",
      }}
      onMouseEnter={(e) => {
        if (!active) e.currentTarget.style.background = "#f6f4f0";
      }}
      onMouseLeave={(e) => {
        if (!active) e.currentTarget.style.background = "transparent";
      }}
    >
      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
        {Icon && (
          <span
            style={{
              opacity: active ? 0.9 : 0.5,
              display: "grid",
              placeItems: "center",
            }}
          >
            <Icon />
          </span>
        )}
        {label}
      </div>
      {badge && (
        <span
          style={{
            background: "var(--accent)",
            color: "#fff",
            fontSize: "10px",
            fontWeight: 700,
            padding: "2px 6px",
            borderRadius: 99,
          }}
        >
          {badge}
        </span>
      )}
    </Link>
  );
}

function SectionHeader({ children }: { children: React.ReactNode }) {
  return (
    <div
      style={{
        fontSize: "10px",
        fontWeight: 600,
        color: "#a09a90",
        letterSpacing: "0.06em",
        textTransform: "uppercase",
        padding: "16px 10px 6px",
      }}
    >
      {children}
    </div>
  );
}

export default function AgencyLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const params = useParams();
  const pathname = usePathname();
  const workspace = params.workspace as string;
  const { data: session } = useSession();

  const userInitial =
    session?.user?.name?.[0]?.toUpperCase() ??
    session?.user?.email?.[0]?.toUpperCase() ??
    "?";

  // The client list is currently mocked, but in the future this would be fetched from the DB
  const clients = [
    { id: "apex", name: "Apex Plumbing" },
    { id: "barton", name: "Barton Creek HVAC" },
  ];

  return (
    <div
      style={{
        display: "flex",
        height: "100vh",
        background: "#fcfbfa",
        fontFamily: "var(--font-sans)",
      }}
    >
      {/* ── LEFT SIDEBAR (Cadence Style) ── */}
      <div
        style={{
          width: 240,
          borderRight: "1px solid #eae6de",
          background: "#f5f4ef",
          display: "flex",
          flexDirection: "column",
        }}
      >
        {/* Workspace Switcher */}
        <div
          style={{
            padding: "16px 16px 12px",
            borderBottom: "1px solid #eae6de",
          }}
        >
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <div
              style={{
                width: 24,
                height: 24,
                borderRadius: 6,
                background: "var(--accent)",
                color: "#fff",
                display: "grid",
                placeItems: "center",
                fontWeight: 700,
                fontSize: "12px",
                textTransform: "uppercase",
              }}
            >
              {typeof workspace === "string" ? workspace.charAt(0) : "A"}
            </div>
            <div style={{ display: "flex", flexDirection: "column" }}>
              <span
                style={{
                  fontSize: "14px",
                  fontWeight: 600,
                  color: "#1a1a1a",
                  lineHeight: 1.2,
                  textTransform: "capitalize",
                }}
              >
                {typeof workspace === "string"
                  ? workspace.replace(/-/g, " ")
                  : "Atlas Agency"}
              </span>
              <span style={{ fontSize: "12px", color: "#6b6560" }}>
                Pro · 2 members
              </span>
            </div>
          </div>
        </div>

        {/* Global Search */}
        <div style={{ padding: "12px 12px 0" }}>
          <div
            style={{
              display: "flex",
              alignItems: "center",
              gap: 8,
              background: "#fff",
              border: "1px solid #eae6de",
              borderRadius: 6,
              padding: "6px 10px",
              color: "#a09a90",
              fontSize: "13px",
            }}
          >
            <Icons.Search />
            <span>Search or jump to...</span>
            <kbd
              style={{
                marginLeft: "auto",
                fontSize: "10px",
                fontFamily: "var(--font-mono)",
                background: "#f5f4ef",
                padding: "2px 4px",
                borderRadius: 4,
              }}
            >
              ⌘K
            </kbd>
          </div>
        </div>

        {/* Navigation */}
        <div style={{ flex: 1, overflowY: "auto", padding: "8px 8px 24px" }}>
          <SectionHeader>Growth (CRM)</SectionHeader>
          <NavItem
            icon={Icons.Target}
            label="Find Clients"
            href={`/${workspace}/agency`}
            active={pathname === `/${workspace}/agency`}
          />
          <NavItem icon={Icons.Kanban} label="Pipeline" badge="3" href="#" />
          <NavItem
            icon={Icons.FileText}
            label="Proposals & Agreements"
            href="#"
          />
          <NavItem icon={Icons.Users} label="Clients / Contacts" href="#" />

          <SectionHeader>Clients</SectionHeader>

          {clients.map((client) => {
            const clientPath = `/${workspace}/agency/client/${client.id}`;
            const isActive = pathname.startsWith(clientPath);
            return (
              <NavItem
                key={client.id}
                icon={Icons.Folder}
                label={client.name}
                href={clientPath}
                active={isActive}
              />
            );
          })}

          <SectionHeader>Finance & Ops</SectionHeader>
          <NavItem
            icon={Icons.CreditCard}
            label="Invoices & Payments"
            href="#"
          />
          <NavItem icon={Icons.TrendingDown} label="Expenses" href="#" />
          <NavItem icon={Icons.Users} label="Users" href="#" />
          <NavItem icon={Icons.Settings} label="Settings" href="#" />
        </div>

        {/* ── User footer ── */}
        <div
          style={{
            padding: "12px 14px",
            borderTop: "1px solid #eae6de",
            display: "flex",
            alignItems: "center",
            justifyContent: "flex-start",
            gap: 9,
            flexShrink: 0,
          }}
        >
          <div
            style={{
              width: 26,
              height: 26,
              borderRadius: "50%",
              background: "#f0ece4",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              fontSize: "0.7rem",
              fontWeight: 600,
              color: "#8a8478",
              flexShrink: 0,
              cursor: "default",
            }}
          >
            {userInitial}
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div
              style={{
                fontSize: "0.76rem",
                fontWeight: 500,
                color: "#1a1a1a",
                overflow: "hidden",
                textOverflow: "ellipsis",
                whiteSpace: "nowrap",
              }}
            >
              {session?.user?.name ??
                session?.user?.email?.split("@")[0] ??
                "Account"}
            </div>
            <button
              onClick={() => signOut({ callbackUrl: "/signin" })}
              style={{
                background: "none",
                border: "none",
                padding: 0,
                fontSize: "0.62rem",
                color: "#a09a90",
                cursor: "pointer",
                fontFamily: "var(--font-sans)",
              }}
            >
              Sign out
            </button>
          </div>
        </div>
      </div>

      {/* ── MAIN CONTENT AREA ── */}
      <div style={{ flex: 1, overflowY: "auto" }}>{children}</div>
    </div>
  );
}
