import { createFileRoute, useNavigate, Link } from "@tanstack/react-router";
import {
  Loader2,
  TrendingUp,
  AlertTriangle,
  Sparkles,
  Plane,
  MapPin,
  Newspaper,
  Globe,
  Lightbulb,
  Clock,
  Plus,
  Check,
  ArrowRight,
  X,
} from "lucide-react";
import { useState } from "react";
import { addCustomAction, useCustomActions } from "@/lib/customActions";
import { useDismissedActions } from "@/lib/dismissedActions";
import { toast } from "sonner";
import { AppShell } from "@/components/AppShell";
import { PortfolioPrompt } from "@/components/PortfolioPrompt";
import { PageHeader } from "@/components/PageHeader";
import { BriefingSkeleton } from "@/components/BriefingSkeleton";
import { Button } from "@/components/ui/button";
import { Sources } from "@/components/Sources";
import { useBriefing } from "@/hooks/useBriefing";
import { useT } from "@/hooks/useSettings";
import type {
  EvidenceItem,
  TravelIndicator,
  LocationTrend,
  NewsItem,
  AiRecommendation,
} from "@/lib/briefing.functions";

export const Route = createFileRoute("/industry")({
  head: () => ({
    meta: [
      { title: "Industry Analysis — The Daily Ledger" },
      {
        name: "description",
        content:
          "Travel demand, location trends, Malaysia & global news, and AI-powered moves — every claim backed by reachable sources.",
      },
      { property: "og:title", content: "Industry Analysis — The Daily Ledger" },
      {
        property: "og:description",
        content: "Evidence-grounded market view tailored to your hotel.",
      },
    ],
  }),
  component: IndustryPage,
});

function IndustryPage() {
  const { hotel, isAllHotels, industryData, isHotelLoading, isIndustryLoading, industryError, refresh } = useBriefing();
  const error = industryError;
  const briefing = industryData;
  const isBriefingLoading = isIndustryLoading;
  const t = useT();
  const navigate = useNavigate();

  if (isHotelLoading) {
    return (
      <div className="flex min-h-dvh items-center justify-center">
        <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
      </div>
    );
  }
  if (isAllHotels || !hotel) return <PortfolioPrompt pageTitle={t("nav.industry")} />;

  const segment = hotel.segment ?? "Mid-market";
  const ia = briefing?.industry_analysis;

  const openDeepDive = () => {
    if (!briefing || !ia) return;
    navigate({
      to: "/deep-dive",
      search: {
        topic: "industry",
        subjectKey: `industry|${segment}|${hotel.location}`,
        title: t("industry.title", { segment, location: hotel.location }),
        context: `Hotel: ${hotel.hotel_name} (${hotel.star_rating ?? "?"}★ ${hotel.property_type ?? ""}, ${segment} segment), located in ${hotel.location}.
Currency: ${hotel.currency || "MYR"}.
Segment outlook: ${ia.segment_outlook}
Benchmark ADR: ${hotel.currency || "MYR"} ${ia.benchmark_adr_myr.toFixed(0)}
Benchmark Occupancy: ${ia.benchmark_occupancy_pct.toFixed(0)}%
Demand drivers: ${ia.demand_drivers.map((d) => d.text).join("; ")}
Risks: ${ia.risks.map((r) => r.text).join("; ")}`,
      },
    });
  };

  return (
    <AppShell hotel={hotel} isLoading={isBriefingLoading} onRefresh={refresh}>
      <PageHeader
        eyebrow={t("industry.eyebrow")}
        title={t("industry.title", { segment, location: hotel.location })}
        subtitle={t("industry.subtitle", { segment: segment.toLowerCase(), hotel: hotel.hotel_name })}
      />

      {error ? (
        <div className="rounded-2xl border border-destructive/30 bg-destructive/5 p-6 text-sm text-destructive">
          <strong className="font-semibold">{t("industry.error")}</strong>
          <p className="mt-1 text-destructive/80">{(error as Error).message}</p>
          <Button size="sm" variant="outline" className="mt-4" onClick={refresh}>
            {t("common.tryAgain")}
          </Button>
        </div>
      ) : isBriefingLoading || !ia ? (
        <BriefingSkeleton />
      ) : (
        <div className="space-y-10">
          {/* Headline outlook */}
          <article className="rounded-2xl border bg-card p-5 shadow-[var(--shadow-elegant)] sm:p-8 md:p-10">
            <div className="mb-4 inline-flex items-center gap-2 text-xs uppercase tracking-[0.18em] text-accent">
              <TrendingUp className="h-3.5 w-3.5" />
              {t("industry.outlookEyebrow")}
            </div>
            <p className="font-serif text-xl italic leading-relaxed text-foreground text-balance sm:text-2xl">
              {ia.segment_outlook}
            </p>
            <Sources items={ia.sources} label={t("common.backedBy")} />
            <Button size="sm" variant="default" className="mt-4" onClick={openDeepDive}>
              <Sparkles className="mr-1.5 h-3.5 w-3.5" />
              {t("common.viewDeepDive")}
            </Button>
          </article>

          {/* Benchmarks */}
          <div className="grid gap-5 sm:grid-cols-2">
            <BenchmarkCard
              label={t("industry.benchmark.adr")}
              value={`${hotel.currency || "MYR"} ${ia.benchmark_adr_myr.toFixed(0)}`}
              hint={t("industry.benchmark.adr.hint")}
            />
            <BenchmarkCard
              label={t("industry.benchmark.occ")}
              value={`${ia.benchmark_occupancy_pct.toFixed(0)}%`}
              hint={t("industry.benchmark.occ.hint")}
            />
          </div>

          {/* Drivers vs risks — each with own sources */}
          <div className="grid gap-5 md:grid-cols-2">
            <article className="rounded-2xl border bg-card p-5 shadow-[var(--shadow-elegant)] sm:p-7">
              <div className="mb-4 inline-flex items-center gap-2 text-xs uppercase tracking-wider text-accent">
                <TrendingUp className="h-3.5 w-3.5" /> {t("industry.drivers")}
              </div>
              <ul className="space-y-4">
                {ia.demand_drivers.map((d, i) => (
                  <EvidenceRow key={i} item={d} positive />
                ))}
              </ul>
            </article>

            <article className="rounded-2xl border bg-card p-5 shadow-[var(--shadow-elegant)] sm:p-7">
              <div className="mb-4 inline-flex items-center gap-2 text-xs uppercase tracking-wider text-destructive">
                <AlertTriangle className="h-3.5 w-3.5" /> {t("industry.risks")}
              </div>
              <ul className="space-y-4">
                {ia.risks.map((r, i) => (
                  <EvidenceRow key={i} item={r} positive={false} />
                ))}
              </ul>
            </article>
          </div>

          {/* Travel demand indicators */}
          {ia.travel_indicators?.length ? (
            <Section icon={Plane} eyebrow="Travel demand indicators" title="Arrivals, tourism, events">
              <div className="grid gap-4 md:grid-cols-2">
                {ia.travel_indicators.map((ti, i) => (
                  <IndicatorCard key={i} item={ti} />
                ))}
              </div>
            </Section>
          ) : null}

          {/* Location-based trends */}
          {ia.location_trends?.length ? (
            <Section icon={MapPin} eyebrow="Location trends" title={`Sub-areas of ${hotel.location}`}>
              <div className="grid gap-4 md:grid-cols-2">
                {ia.location_trends.map((lt, i) => (
                  <LocationCard key={i} item={lt} />
                ))}
              </div>
            </Section>
          ) : null}

          {/* Malaysia news (PRIMARY) */}
          {ia.malaysia_news?.length ? (
            <Section icon={Newspaper} eyebrow="Malaysia news" title="Local policy, economy & campaigns">
              <div className="space-y-4">
                {ia.malaysia_news.map((n, i) => (
                  <NewsCard key={i} item={n} />
                ))}
              </div>
            </Section>
          ) : null}

          {/* International news (SECONDARY) */}
          {ia.international_news?.length ? (
            <Section icon={Globe} eyebrow="Global signals" title="Chains, OTAs, tech">
              <div className="space-y-4">
                {ia.international_news.map((n, i) => (
                  <NewsCard key={i} item={n} />
                ))}
              </div>
            </Section>
          ) : null}

          {/* AI Recommendations */}
          {ia.ai_recommendations?.length ? (
            <Section icon={Lightbulb} eyebrow="AI recommendations" title="What to do, based on the signals">
              <p className="-mt-2 mb-4 text-sm text-muted-foreground">
                Add any of these to your Action Plan to track progress.
              </p>
              <div className="space-y-4">
                {ia.ai_recommendations.map((r, i) => (
                  <RecommendationCard key={i} item={r} sourceLabel={`Industry · ${segment}`} />
                ))}
              </div>
              <div className="mt-5 flex justify-end">
                <Button asChild variant="outline" size="sm" className="gap-1.5">
                  <Link to="/actions">Open Action Plan <ArrowRight className="h-3.5 w-3.5" /></Link>
                </Button>
              </div>
            </Section>
          ) : null}
        </div>
      )}
    </AppShell>
  );
}

function BenchmarkCard({ label, value, hint }: { label: string; value: string; hint: string }) {
  return (
    <div className="rounded-2xl border bg-gradient-to-br from-brand-soft/30 to-card p-5 shadow-[var(--shadow-elegant)] sm:p-7">
      <div className="text-xs uppercase tracking-wider text-muted-foreground">{label}</div>
      <div className="mt-2 font-serif text-3xl font-medium text-brand sm:text-4xl md:text-5xl">{value}</div>
      <div className="mt-1 text-xs text-muted-foreground">{hint}</div>
    </div>
  );
}

function EvidenceRow({ item, positive }: { item: EvidenceItem; positive: boolean }) {
  return (
    <li className="flex gap-3 text-foreground">
      <span
        className={`mt-1 inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-full text-xs ${
          positive ? "bg-accent/15 text-accent" : "bg-destructive/10 text-destructive"
        }`}
      >
        {positive ? "▲" : "▼"}
      </span>
      <div className="min-w-0 flex-1">
        <p className="leading-relaxed">{item.text}</p>
        <Sources items={item.sources} />
      </div>
    </li>
  );
}

function Section({
  icon: Icon,
  eyebrow,
  title,
  children,
}: {
  icon: typeof Plane;
  eyebrow: string;
  title: string;
  children: React.ReactNode;
}) {
  return (
    <section>
      <div className="mb-4">
        <div className="inline-flex items-center gap-2 text-xs uppercase tracking-[0.18em] text-accent">
          <Icon className="h-3.5 w-3.5" /> {eyebrow}
        </div>
        <h2 className="mt-1 font-serif text-xl font-medium text-foreground sm:text-2xl">{title}</h2>
      </div>
      {children}
    </section>
  );
}

function IndicatorCard({ item }: { item: TravelIndicator }) {
  return (
    <article className="rounded-2xl border bg-card p-5 shadow-[var(--shadow-elegant)]">
      <div className="text-xs uppercase tracking-wider text-muted-foreground">{item.label}</div>
      <div className="mt-1.5 font-serif text-2xl font-medium text-brand">{item.value}</div>
      <p className="mt-2 text-sm leading-relaxed text-foreground">👉 {item.insight}</p>
      <Sources items={item.sources} />
    </article>
  );
}

function LocationCard({ item }: { item: LocationTrend }) {
  const tone =
    item.impact === "positive"
      ? "border-accent/30 bg-accent/5"
      : item.impact === "negative"
        ? "border-destructive/30 bg-destructive/5"
        : "border-border bg-card";
  return (
    <article className={`rounded-2xl border p-5 shadow-[var(--shadow-elegant)] ${tone}`}>
      <div className="flex items-center gap-2">
        <MapPin className="h-4 w-4 text-accent" />
        <h3 className="font-serif text-lg font-medium text-foreground">{item.area}</h3>
      </div>
      <p className="mt-2 text-sm leading-relaxed text-foreground">{item.trend}</p>
      <Sources items={item.sources} />
    </article>
  );
}

function NewsCard({ item }: { item: NewsItem }) {
  return (
    <article className="rounded-2xl border bg-card p-5 shadow-[var(--shadow-elegant)]">
      <div className="mb-1 text-[10px] font-medium uppercase tracking-wider text-accent">
        {item.category}
      </div>
      <h3 className="font-serif text-base font-medium text-foreground sm:text-lg">{item.headline}</h3>
      <p className="mt-1.5 text-sm leading-relaxed text-muted-foreground">{item.summary}</p>
      <p className="mt-2 rounded-lg bg-brand-soft/30 px-3 py-2 text-sm text-foreground">
        👉 {item.insight}
      </p>
      <Sources items={item.sources} />
    </article>
  );
}

function RecommendationCard({ item, sourceLabel }: { item: AiRecommendation; sourceLabel: string }) {
  const urgencyColor = {
    today: "text-destructive",
    this_week: "text-amber-700",
    this_month: "text-muted-foreground",
  }[item.urgency];
  const custom = useCustomActions();
  const dismissed = useDismissedActions();
  const dismissKey = `industry:${sourceLabel}:${item.recommendation}`;
  const [added, setAdded] = useState(false);
  const alreadyAdded =
    added || custom.items.some((a) => a.title === item.recommendation && a.source_label === sourceLabel);
  const handleAdd = () => {
    addCustomAction({
      title: item.recommendation,
      why: item.rationale,
      category: "Marketing",
      urgency: item.urgency,
      source_label: sourceLabel,
    });
    setAdded(true);
    toast.success("Added to Action Plan");
  };
  if (dismissed.has(dismissKey)) {
    return (
      <article className="flex items-center justify-between gap-3 rounded-2xl border border-dashed bg-muted/20 px-4 py-3 text-sm text-muted-foreground">
        <span className="line-through">{item.recommendation}</span>
        <Button size="sm" variant="ghost" className="h-7 gap-1 text-xs" onClick={() => dismissed.restore(dismissKey)}>
          Restore
        </Button>
      </article>
    );
  }
  return (
    <article className="rounded-2xl border border-brand/30 bg-gradient-to-br from-brand-soft/30 to-card p-5 shadow-[var(--shadow-elegant)]">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <div className="flex items-center gap-3">
          <Lightbulb className="h-4 w-4 text-brand" />
          <span className={`inline-flex items-center gap-1 text-[10px] font-medium uppercase tracking-wider ${urgencyColor}`}>
            <Clock className="h-3 w-3" /> {item.urgency.replace("_", " ")}
          </span>
        </div>
        <Button
          size="sm"
          variant="ghost"
          className="h-7 gap-1 px-2 text-xs text-muted-foreground"
          onClick={() => { dismissed.dismiss(dismissKey); toast("Dismissed"); }}
          title="Not relevant"
        >
          <X className="h-3.5 w-3.5" /> Dismiss
        </Button>
      </div>
      <h3 className="mt-1.5 font-serif text-base font-medium text-foreground sm:text-lg">
        {item.recommendation}
      </h3>
      <p className="mt-1.5 text-sm leading-relaxed text-muted-foreground">{item.rationale}</p>
      <Sources items={item.sources} />
      <div className="mt-4 flex justify-end">
        <Button
          size="sm"
          variant={alreadyAdded ? "outline" : "default"}
          onClick={handleAdd}
          disabled={alreadyAdded}
          className="gap-1.5"
        >
          {alreadyAdded ? <Check className="h-3.5 w-3.5" /> : <Plus className="h-3.5 w-3.5" />}
          {alreadyAdded ? "Added to Actions" : "Add to Action Plan"}
        </Button>
      </div>
    </article>
  );
}
