"use client";

/**
 * PticaPageContent — client root of the ПТИЦА cockpit.
 *
 * Wires the SAME /analyze data as the existing light analysis page via
 * useParcelAnalyzeQuery, narrows the response to ParcelAnalysis (the sanctioned
 * `as unknown as` pattern — see AnalysisPageContent.tsx:111), and composes the
 * dark operator-terminal shell.
 *
 * PR#4 — DETAIL DRAWER system: this root owns the open-drawer state
 * (`openDrawer: DrawerKey | null`), threads an `onOpenDrawer(key)` callback down
 * the tree (hero cards + scan cards), and renders the matching drawer content
 * inside a single controlled <PticaDrawer>. Deep-link: `?drawer=<key>` opens a
 * drawer on mount; opening/closing updates the URL query via `router.replace`
 * (shallow, no full navigation) so drawers are linkable / back-button friendly.
 *
 * The root carries BOTH `.pticaRoot` and `data-theme="dark"` so the scoped dark
 * tokens apply here and never leak to the light pages.
 */

import { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { usePathname, useRouter, useSearchParams } from "next/navigation";

import styles from "./ptica.module.css";
import {
  useParcelAnalyzeQuery,
  useParcelForecastQuery,
} from "@/lib/site-finder-api";
import type { ParcelAnalysis } from "@/types/site-finder";
import { PticaShell } from "@/components/site-finder/ptica/PticaShell";
import type { PticaTab } from "@/components/site-finder/ptica/PticaShell";
import { PticaHero } from "@/components/site-finder/ptica/PticaHero";
import { DevelopmentScan } from "@/components/site-finder/ptica/DevelopmentScan";
import { PticaLowerGrid } from "@/components/site-finder/ptica/cockpit/PticaLowerGrid";
import { PticaBottomGrid } from "@/components/site-finder/ptica/cockpit/PticaBottomGrid";
import { PticaScenarios } from "@/components/site-finder/ptica/scenarios/PticaScenarios";
import { PticaReports } from "@/components/site-finder/ptica/reports/PticaReports";
import { PticaCompare } from "@/components/site-finder/ptica/compare/PticaCompare";
import { PticaDrawer } from "@/components/site-finder/ptica/drawers/PticaDrawer";
import { getDrawerEntry } from "@/components/site-finder/ptica/drawers/drawer-registry";
import {
  asDrawerKey,
  type DrawerKey,
} from "@/components/site-finder/ptica/drawers/drawer-keys";

interface Props {
  cad: string;
}

export function PticaPageContent({ cad }: Props) {
  const [horizon, setHorizon] = useState<number>(12);
  const [tab, setTab] = useState<PticaTab>("analysis");
  const { data, isLoading, error } = useParcelAnalyzeQuery(cad, horizon);
  // §22 forecast is keyed/cached by cad — call unconditionally; it polls the
  // async report (enqueued by /analyze) and feeds both the hero invest-score and
  // the Scenarios tab. Pending state is handled inside each consumer.
  const { data: forecastData } = useParcelForecastQuery(cad);
  const forecastReport =
    forecastData?.status === "ready" ? forecastData.report : undefined;

  // ── Drawer open-state + deep-link (?drawer=<key>) ──────────────────────────
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const [openDrawer, setOpenDrawer] = useState<DrawerKey | null>(null);

  // On mount / URL change, sync the open drawer from the `?drawer=` query.
  const drawerParam = searchParams.get("drawer");
  useEffect(() => {
    setOpenDrawer(asDrawerKey(drawerParam));
  }, [drawerParam]);

  // Update the URL query shallowly (no full navigation) when opening/closing.
  const syncUrl = useCallback(
    (key: DrawerKey | null) => {
      const params = new URLSearchParams(searchParams.toString());
      if (key) params.set("drawer", key);
      else params.delete("drawer");
      const qs = params.toString();
      router.replace(qs ? `${pathname}?${qs}` : pathname, { scroll: false });
    },
    [router, pathname, searchParams],
  );

  const handleOpenDrawer = useCallback(
    (key: DrawerKey) => {
      setOpenDrawer(key);
      syncUrl(key);
    },
    [syncUrl],
  );

  const handleCloseDrawer = useCallback(() => {
    setOpenDrawer(null);
    syncUrl(null);
  }, [syncUrl]);

  // ── Loading ────────────────────────────────────────────────────────────────
  if (isLoading) {
    return (
      <div className={styles.pticaRoot} data-theme="dark">
        <div className={styles.stateScreen}>
          <div className={styles.stateBox}>Анализируем участок {cad}…</div>
        </div>
      </div>
    );
  }

  // ── Error ──────────────────────────────────────────────────────────────────
  if (error || !data) {
    const msg =
      error instanceof Error ? error.message : "Ошибка загрузки анализа";
    return (
      <div className={styles.pticaRoot} data-theme="dark">
        <div className={styles.stateScreen}>
          <div>
            <div className={styles.stateError}>{msg}</div>
            <Link href="/site-finder" className={styles.stateLink}>
              ← Вернуться к Site Finder
            </Link>
          </div>
        </div>
      </div>
    );
  }

  // Narrow to ParcelAnalysis (superset of ParcelAnalyzeResponse) — both describe
  // the same /analyze endpoint. Sanctioned pattern (AnalysisPageContent.tsx:111).
  const analysis = data as unknown as ParcelAnalysis;

  const drawerEntry = openDrawer
    ? getDrawerEntry(openDrawer, analysis, forecastReport)
    : null;

  return (
    <div className={styles.pticaRoot} data-theme="dark">
      <PticaShell activeTab={tab} onTabChange={setTab}>
        {tab === "analysis" && (
          <>
            <PticaHero
              analysis={analysis}
              forecastReport={forecastReport}
              onOpenDrawer={handleOpenDrawer}
            />
            <DevelopmentScan
              analysis={analysis}
              onOpenDrawer={handleOpenDrawer}
            />
            <PticaLowerGrid
              analysis={analysis}
              forecastReport={forecastReport}
              onOpenDrawer={handleOpenDrawer}
            />
            <PticaBottomGrid
              analysis={analysis}
              forecastReport={forecastReport}
              onOpenDrawer={handleOpenDrawer}
            />
          </>
        )}
        {tab === "scenarios" && (
          <PticaScenarios
            cad={cad}
            horizon={horizon}
            onHorizonChange={setHorizon}
          />
        )}
        {tab === "reports" && <PticaReports cad={cad} analysis={analysis} />}
        {tab === "compare" && <PticaCompare cad={cad} />}
      </PticaShell>

      <PticaDrawer
        open={Boolean(drawerEntry)}
        title={drawerEntry?.title ?? ""}
        sub={drawerEntry?.sub}
        onClose={handleCloseDrawer}
      >
        {drawerEntry?.content}
      </PticaDrawer>
    </div>
  );
}
