"use client";

import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { Bell, Bot, CalendarClock, CircleDot, Building2, CreditCard, FileText, Globe, ListChecks, Mail, MailCheck, Network, ShieldCheck, Stamp, UserRound, Users, Wallet } from "lucide-react";
import { Field, FieldDescription, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { PageContent, PageHeader } from "@/components/app/page";
import { cn } from "@/lib/utils";
import ProtectedRoute from "../auth/protected-route";
import { useAuth } from "../auth/auth-context";
import AppShell from "../components/app-shell";

const SECTIONS = [
  { href: "/settings", label: "My profile", icon: UserRound, hint: "Name, email and password" },
  { href: "/settings/organization", label: "Organization", icon: Building2, hint: "Name, plan, owner" },
  { href: "/settings/subscription", label: "Subscription", icon: CreditCard, hint: "Plan, renewal and bKash payment" },
  { href: "/settings/payments", label: "Payments & invoicing", icon: Wallet, hint: "Invoice header, bank, defaults", permission: "organization.manage", feature: "payment_invoicing" },
  { href: "/settings/notifications", label: "Notifications", icon: Bell, hint: "Channels per event" },
  { href: "/settings/email-accounts", label: "Email accounts", icon: Mail, hint: "Mailboxes, test, members", permission: "mail.view", feature: "mailbox" },
  { href: "/settings/system-email", label: "System email", icon: MailCheck, hint: "Password resets and alerts", permission: "organization.manage", feature: "mailbox" },
  { href: "/settings/email-templates", label: "Email templates", icon: FileText, hint: "Wording with merge fields", permission: "mail.view", feature: "mailbox" },
  { href: "/settings/portal", label: "Portal access", icon: Globe, hint: "Buyer and factory logins", permissions: ["portal.manage", "portal.view"], feature: "buyer_portal" },
  { href: "/settings/ai-access", label: "AI assistant access", icon: Bot, hint: "Claude, ChatGPT, Codex", feature: "ai_assistant" },
  { href: "/settings/tna-templates", label: "TNA templates", icon: CalendarClock, hint: "Time & action plans", permission: "preproduction.manage", feature: "custom_tna_templates" },
  { href: "/settings/approval-templates", label: "Approval templates", icon: Stamp, hint: "Lab dip, fit, PP sample", permission: "preproduction.manage", feature: "custom_tna_templates" },
  { href: "/settings/reference-data", label: "Reference data", icon: ListChecks, hint: "Lists used in forms", permission: "reference_data.view" },
  { href: "/settings/roles", label: "Roles", icon: ShieldCheck, hint: "Custom access rules", permission: "roles.view" },
  { href: "/settings/departments", label: "Departments", icon: Network, hint: "Team structure", permission: "users.view" },
  { href: "/team", label: "Team members", icon: Users, hint: "Invite and deactivate", permission: "users.view" },
];

/** Shared frame for every settings screen (including /team) so the section nav never disappears. */
export function SettingsLayout({ title, description, actions, children }) {
  return <SettingsShell title={title}>
    <SettingsFrame title={title} description={description} actions={actions}>{children}</SettingsFrame>
  </SettingsShell>;
}

// Auth + app shell only; screens whose header actions need hook state render <SettingsFrame> inside it.
export function SettingsShell({ title, children }) {
  return <ProtectedRoute><AppShell title="Settings" subtitle={title}>{children}</AppShell></ProtectedRoute>;
}

/** Section nav (vertical on desktop, a select on mobile) + page header + content. */
export function SettingsFrame({ title, description, actions, children }) {
  const pathname = usePathname();
  const router = useRouter();
  const { can, organization } = useAuth();
  const entitlements = organization?.subscription?.entitlements || {};
  const sections = SECTIONS.filter((section) => (!section.feature || entitlements[section.feature] !== false) && (section.permissions ? section.permissions.some((permission) => can(permission)) : !section.permission || can(section.permission)));
  const current = sections.find((section) => section.href === pathname);

  return <PageContent>
    <div className="grid gap-6 lg:grid-cols-[220px_minmax(0,1fr)] lg:gap-8">
      <div className="lg:hidden">
        <Select value={current?.href || ""} onValueChange={(href) => router.push(href)}>
          <SelectTrigger className="w-full" aria-label="Settings section"><SelectValue placeholder="Settings section" /></SelectTrigger>
          <SelectContent>
            {sections.map(({ href, label, icon: Icon }) => <SelectItem key={href} value={href}><Icon /> {label}</SelectItem>)}
          </SelectContent>
        </Select>
      </div>

      <nav className="hidden lg:block" aria-label="Settings sections">
        <ul className="sticky top-20 grid gap-1">
          {sections.map(({ href, label, icon: Icon, hint }) => {
            const active = pathname === href;
            return <li key={href}>
              <Link href={href} aria-current={active ? "page" : undefined} className={cn(
                "flex items-start gap-3 rounded-md px-3 py-2 text-sm transition-colors hover:bg-muted focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50",
                active ? "bg-muted font-medium text-foreground" : "text-muted-foreground hover:text-foreground",
              )}>
                <Icon className="mt-0.5 size-4 shrink-0" aria-hidden="true" />
                <span className="grid min-w-0"><span className="truncate">{label}</span><span className="truncate text-xs font-normal text-muted-foreground">{hint}</span></span>
              </Link>
            </li>;
          })}
        </ul>
      </nav>

      <section className="flex min-w-0 flex-col gap-6">
        <PageHeader title={title} description={description} actions={actions} />
        {children}
      </section>
    </div>
  </PageContent>;
}

// A value the user can see but not change here, laid out like the editable fields around it.
export function ReadOnlyField({ id, label, value, description }) {
  return <Field>
    <FieldLabel htmlFor={id}>{label}</FieldLabel>
    <Input id={id} value={value ?? ""} readOnly className="bg-muted/50 text-muted-foreground" />
    {description && <FieldDescription>{description}</FieldDescription>}
  </Field>;
}

export function UnsavedHint({ show, className }) {
  if (!show) return null;
  return <span role="status" className={cn("mr-auto inline-flex items-center gap-1.5 text-xs font-medium text-warning", className)}><CircleDot className="size-3" aria-hidden="true" /> Unsaved changes</span>;
}
