"use client";

import {
  useState,
  type ComponentType,
  type ReactNode,
  type SVGProps,
} from "react";
import Link from "next/link";
import { cn } from "@/lib/utils";
import { Card, Panel, Badge, IconChip, EmptyState } from "./parts";
import { QrCode } from "./charts";
import { useDashboardCtx } from "./context";
import { useVehicles } from "@/hooks/useVehicles";
import { useEmergencyContacts } from "@/hooks/useEmergencyContacts";
import { useSubscription } from "@/hooks/useSubscription";
import { PlanPicker } from "./plan-picker";
import {
  WelcomeBanner,
  LiveAlertBanner,
  AccountStatusPanel,
  QuickActionsPanel,
  KpiCards,
  ScanAnalyticsPanel,
  VehicleOverviewPanel,
  RecentRequestsPanel,
  ActivityFeedPanel,
  VehiclePerformanceTable,
  QrPerformancePanel,
  EmergencyMonitoringPanel,
  EmergencyContactsPanel,
  NotificationsPanel,
  SubscriptionPanel,
} from "./panels";
import {
  PlusIcon,
  ShareIcon,
  DownloadIcon,
  CheckIcon,
  LockIcon,
  BellIcon,
  MapPinIcon,
  ShieldIcon,
  LogOutIcon,
  CarIcon,
  QrIcon,
} from "@/app/components/icons";

type IconType = ComponentType<SVGProps<SVGSVGElement>>;
type ActionFn = (action: string) => void;

function ViewHeader({ title, subtitle }: { title: string; subtitle?: string }) {
  return (
    <div>
      <h1 className="text-xl font-bold text-white">{title}</h1>
      {subtitle && <p className="mt-1 text-sm text-white/50">{subtitle}</p>}
    </div>
  );
}

function AddButton({ onAction }: { onAction: ActionFn }) {
  return (
    <button
      type="button"
      onClick={() => onAction("add")}
      className="inline-flex items-center gap-1.5 rounded-lg bg-brand px-3 py-1.5 text-xs font-semibold text-white transition hover:brightness-110"
    >
      <PlusIcon className="h-4 w-4" />
      Add Vehicle
    </button>
  );
}

/* ---------- Dashboard (overview) ---------- */
export function OverviewView() {
  const { data, onAction } = useDashboardCtx();
  return (
    <div className="space-y-6">
      <WelcomeBanner
        gamification={data.gamification}
        scanCard={data.scanCard}
        isPro={data.user.isPro}
        onAction={onAction}
      />
      <LiveAlertBanner alert={data.liveAlert} onAction={onAction} />
      <KpiCards kpis={data.kpis} />

      <div className="grid gap-6 lg:grid-cols-3">
        <div className="lg:col-span-2">
          <ScanAnalyticsPanel trend={data.scanTrend} />
        </div>
        <VehicleOverviewPanel vehicles={data.vehicles} onAction={onAction} />
      </div>

      <div className="grid gap-6 lg:grid-cols-2">
        <RecentRequestsPanel requests={data.contactRequests} />
        <ActivityFeedPanel activity={data.activity} />
      </div>

      <div className="grid gap-6 lg:grid-cols-2">
        <AccountStatusPanel status={data.accountStatus} />
        <QuickActionsPanel actions={data.quickActions} onAction={onAction} />
      </div>

      <div className="grid gap-6 lg:grid-cols-2">
        <VehiclePerformanceTable rows={data.vehiclePerformance} />
        <QrPerformancePanel qr={data.qrPerformance} />
      </div>

      <div className="grid gap-6 lg:grid-cols-2">
        <EmergencyMonitoringPanel emergency={data.emergency} />
        <SubscriptionPanel subscription={data.subscription} onAction={onAction} />
      </div>
    </div>
  );
}

/* Shared loading / error states for the live GET /vehicle query. */
function SectionLoading({ rows = 3 }: { rows?: number }) {
  return (
    <div className="glass animate-pulse space-y-3 rounded-2xl p-5">
      {Array.from({ length: rows }).map((_, i) => (
        <div key={i} className="h-14 rounded-xl bg-white/5" />
      ))}
    </div>
  );
}

function SectionError({
  message,
  onRetry,
}: {
  message?: string;
  onRetry: () => void;
}) {
  return (
    <div className="glass rounded-2xl p-8 text-center">
      <h3 className="text-sm font-semibold text-white">
        Couldn&apos;t load your vehicles
      </h3>
      <p className="mt-1 text-xs text-white/55">
        {message ?? "Check your connection and try again."}
      </p>
      <button type="button" onClick={onRetry} className="btn-primary mt-4 text-sm">
        Retry
      </button>
    </div>
  );
}

/* ---------- Vehicles ---------- */
export function VehiclesView() {
  const { data, onAction } = useDashboardCtx();
  const {
    data: vehicles,
    isLoading,
    isError,
    error,
    refetch,
  } = useVehicles();

  return (
    <div className="space-y-6">
      <ViewHeader title="Vehicles" subtitle="Manage your registered vehicles" />
      {isLoading ? (
        <SectionLoading />
      ) : isError ? (
        <SectionError message={error?.message} onRetry={() => refetch()} />
      ) : vehicles && vehicles.length > 0 ? (
        <VehicleOverviewPanel
          vehicles={vehicles}
          onAction={onAction}
          action={<AddButton onAction={onAction} />}
        />
      ) : (
        <Panel
          title="Vehicle Overview"
          subtitle="0 registered"
          action={<AddButton onAction={onAction} />}
          bodyClassName="p-0"
        >
          <EmptyState
            icon={CarIcon}
            title="No vehicles yet"
            desc="Add your first vehicle to generate its QR code and start receiving contact requests."
          />
        </Panel>
      )}
      <VehiclePerformanceTable rows={data.vehiclePerformance} />
    </div>
  );
}

/* ---------- QR Codes ---------- */
export function QrView() {
  const { data, onAction } = useDashboardCtx();
  const {
    data: vehicles,
    isLoading,
    isError,
    error,
    refetch,
  } = useVehicles();

  return (
    <div className="space-y-6">
      <ViewHeader title="QR Codes" subtitle="Generate, share and download vehicle QR codes" />
      {isLoading ? (
        <SectionLoading rows={2} />
      ) : isError ? (
        <SectionError message={error?.message} onRetry={() => refetch()} />
      ) : vehicles && vehicles.length > 0 ? (
        <div className="grid gap-5 sm:grid-cols-2 xl:grid-cols-3">
          {vehicles.map((v) => (
            <Card key={v.id} className="flex flex-col items-center p-5 text-center">
              <div className="rounded-xl bg-white p-3 shadow-lg">
                <QrCode value={v.number} />
              </div>
              <p className="mt-3 font-semibold text-white">{v.number}</p>
              <div className="mt-1.5">
                <Badge tone={v.qrActive ? "success" : "neutral"}>
                  {v.qrActive ? "QR Active" : "Inactive"}
                </Badge>
              </div>
              <div className="mt-4 flex w-full gap-2">
                <button
                  type="button"
                  onClick={() => onAction("share")}
                  className="btn-primary flex-1 text-xs"
                >
                  <ShareIcon className="h-4 w-4" />
                  Share
                </button>
                <button
                  type="button"
                  onClick={() => onAction("download")}
                  className="btn-ghost flex-1 text-xs"
                >
                  <DownloadIcon className="h-4 w-4" />
                  Download
                </button>
              </div>
            </Card>
          ))}
        </div>
      ) : (
        <Card>
          <EmptyState
            icon={QrIcon}
            title="No QR codes yet"
            desc="Add a vehicle to generate its first QR code."
          />
        </Card>
      )}
      <QrPerformancePanel qr={data.qrPerformance} />
    </div>
  );
}

/* ---------- Requests ---------- */
export function RequestsView() {
  const { data } = useDashboardCtx();
  return (
    <div className="space-y-6">
      <ViewHeader title="Requests" subtitle="All contact requests across your vehicles" />
      <RecentRequestsPanel requests={data.contactRequests} />
    </div>
  );
}

/* ---------- Activity ---------- */
export function ActivityView() {
  const { data } = useDashboardCtx();
  return (
    <div className="space-y-6">
      <ViewHeader title="Activity Logs" subtitle="Real-time timeline of vehicle interactions" />
      <ActivityFeedPanel activity={data.activity} />
    </div>
  );
}

/* ---------- Analytics ---------- */
export function AnalyticsView() {
  const { data } = useDashboardCtx();
  return (
    <div className="space-y-6">
      <ViewHeader title="Analytics" subtitle="Scan performance and engagement insights" />
      <ScanAnalyticsPanel trend={data.scanTrend} />
      <div className="grid gap-6 lg:grid-cols-2">
        <QrPerformancePanel qr={data.qrPerformance} />
      </div>
      <VehiclePerformanceTable rows={data.vehiclePerformance} />
    </div>
  );
}

/* ---------- Emergency ---------- */
export function EmergencyView() {
  const { data, onAction } = useDashboardCtx();
  const { data: contacts, isLoading, isError, refetch } = useEmergencyContacts();
  return (
    <div className="space-y-6">
      <ViewHeader title="Emergency Contacts" subtitle="Safety monitoring and SOS configuration" />
      <EmergencyMonitoringPanel
        emergency={
          contacts
            ? { ...data.emergency, contactsConfigured: contacts.length }
            : data.emergency
        }
      />
      <EmergencyContactsPanel
        contacts={contacts ?? []}
        isLoading={isLoading}
        isError={isError}
        onRetry={() => refetch()}
        onAction={onAction}
      />
    </div>
  );
}

/* ---------- Notifications ---------- */
export function NotificationsView() {
  const { data } = useDashboardCtx();
  return (
    <div className="space-y-6">
      <ViewHeader title="Notifications" subtitle="Alerts, requests and system updates" />
      <NotificationsPanel notifications={data.notifications} />
    </div>
  );
}

/* ---------- Billing ---------- */
export function BillingView() {
  const { data, onAction } = useDashboardCtx();
  // Prefer the dedicated endpoint (fresh after a plan change) and fall back to
  // the copy embedded in the dashboard payload on first paint.
  const live = useSubscription();
  const subscription = live.data ?? data.subscription;

  return (
    <div className="space-y-6">
      <ViewHeader title="Billing" subtitle="Plan, usage and payments" />

      {/* Without this the page silently renders the placeholder view-model
          (Free, 1/1 vehicles) whenever the API is unreachable — which reads as
          a real, and wrong, subscription. */}
      {live.isError && (
        <p
          role="alert"
          className="rounded-xl border border-warning/30 bg-warning/10 px-4 py-3 text-sm text-warning"
        >
          Couldn&apos;t load your subscription, so the plan shown below may be out
          of date. Please refresh in a moment.
        </p>
      )}

      <div className="grid gap-6 lg:grid-cols-2">
        <SubscriptionPanel subscription={subscription} onAction={onAction} />
        <Panel title="Plan Features" subtitle="What's included">
          <ul className="space-y-2.5">
            {subscription.features.map((f) => (
              <li key={f} className="flex items-center gap-2 text-sm text-white/80">
                <CheckIcon className="h-4 w-4 shrink-0 text-success" />
                {f}
              </li>
            ))}
          </ul>
        </Panel>
      </div>
      <PlanPicker />
    </div>
  );
}

/* ---------- Settings ---------- */
function Toggle({ defaultOn }: { defaultOn?: boolean }) {
  const [on, setOn] = useState(!!defaultOn);
  return (
    <button
      type="button"
      role="switch"
      aria-checked={on}
      onClick={() => setOn((o) => !o)}
      className={cn(
        "relative h-6 w-11 shrink-0 rounded-full transition-colors",
        on ? "bg-brand" : "bg-white/15",
      )}
    >
      <span
        className={cn(
          "absolute top-0.5 h-5 w-5 rounded-full bg-white transition-all",
          on ? "left-[1.375rem]" : "left-0.5",
        )}
      />
    </button>
  );
}

function SettingRow({
  icon: Icon,
  label,
  desc,
  control,
}: {
  icon: IconType;
  label: string;
  desc?: string;
  control: ReactNode;
}) {
  return (
    <div className="flex items-center gap-3 border-b border-white/5 px-5 py-4 last:border-0">
      <IconChip icon={Icon} tone="neutral" className="h-9 w-9" />
      <div className="min-w-0 flex-1">
        <p className="text-sm font-medium text-white">{label}</p>
        {desc && <p className="text-xs text-white/45">{desc}</p>}
      </div>
      {control}
    </div>
  );
}

export function SettingsView() {
  const { name, email, initials, loggingOut, onLogout } = useDashboardCtx();
  return (
    <div className="space-y-6">
      <ViewHeader title="Settings" subtitle="Manage your account and preferences" />

      <Panel title="Account">
        <div className="flex items-center gap-4">
          <span
            className="grid h-16 w-16 shrink-0 place-items-center rounded-full text-lg font-bold text-white"
            style={{ background: "linear-gradient(135deg,#5c7cfa,#9b6bff)" }}
          >
            {initials}
          </span>
          <div className="min-w-0">
            <p className="truncate text-base font-semibold text-white">{name}</p>
            {email && <p className="truncate text-sm text-white/50">{email}</p>}
            <span className="mt-1 inline-flex items-center gap-1 rounded-full bg-brand/12 px-2.5 py-0.5 text-[11px] font-semibold text-brand">
              Premium Member
            </span>
          </div>
        </div>
      </Panel>

      <Panel title="Preferences" bodyClassName="p-0">
        <SettingRow
          icon={LockIcon}
          label="Private contact mode"
          desc="Hide your number on every QR scan"
          control={<Toggle defaultOn />}
        />
        <SettingRow
          icon={BellIcon}
          label="Push notifications"
          desc="Scan alerts and contact requests"
          control={<Toggle defaultOn />}
        />
        <SettingRow
          icon={MapPinIcon}
          label="Location insights"
          desc="Use scan locations for analytics"
          control={<Toggle />}
        />
        <SettingRow
          icon={ShieldIcon}
          label="Privacy policy"
          control={
            <Link href="/privacy-policy" className="text-xs font-semibold text-brand hover:underline">
              View
            </Link>
          }
        />
      </Panel>

      <button
        type="button"
        onClick={onLogout}
        disabled={loggingOut}
        className="flex w-full items-center justify-center gap-2 rounded-xl border border-danger/30 bg-danger/10 px-5 py-3.5 text-sm font-semibold text-danger transition hover:bg-danger/15 disabled:cursor-not-allowed disabled:opacity-60 sm:w-auto"
      >
        <LogOutIcon className="h-4 w-4" />
        {loggingOut ? "Signing out…" : "Log out"}
      </button>
    </div>
  );
}
