import { createFileRoute, Link } from "@tanstack/react-router";
import { useEffect, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import {
  ScanLine,
  CalendarCheck,
  ReceiptText,
  Sparkles,
  Bug,
  ShieldCheck,
  FileText,
  ClipboardList,
  ArrowRight,
  Thermometer,
  Droplets,
  History,
  Building2,
  BookOpen,
} from "lucide-react";
import { AppShell, BrandMark } from "@/components/AppShell";
import { supabase } from "@/integrations/supabase/client";
import { scanRequiresPayment, useAppSettings } from "@/lib/settings";
import heroImage from "@/assets/hero-scan.jpg";

export const Route = createFileRoute("/")({
  head: () => ({
    meta: [
      { title: "Emma Mold Inspection Services | AI Mold Checks & Treatment" },
      {
        name: "description",
        content:
          "Check suspicious spots with an AI-assisted photo assessment, then book professional mold inspection, treatment, cleaning and fumigation.",
      },
      { property: "og:title", content: "Emma Mold Inspection Services" },
      {
        property: "og:description",
        content: "Protecting homes from mold: inspection, cleaning and fumigation with AI-assisted photo checks.",
      },
    ],
  }),
  component: Index,
});

const onboarding = [
  {
    title: "Detect Mold Early",
    text: "Take a clear photo of suspicious mold and receive an AI-assisted preliminary visual assessment.",
  },
  {
    title: "Book Professional Inspection",
    text: "Book mold inspections, mold treatment, cleaning services, fumigation, and pest control.",
  },
  {
    title: "Protect Your Property",
    text: "Receive professional reports, before-and-after photos, and expert recommendations.",
  },
];

const actions = [
  { to: "/check", label: "Check for Mold", icon: ScanLine, tone: "bg-brand text-primary-foreground" },
  { to: "/thermal", label: "Thermal Inspection", icon: Thermometer, tone: "bg-card" },
  { to: "/book", label: "Book Inspection", icon: CalendarCheck, tone: "bg-card" },
  { to: "/book", label: "Request Quote", icon: ReceiptText, tone: "bg-card" },
  { to: "/services", label: "Cleaning Services", icon: Sparkles, tone: "bg-card" },
  { to: "/services", label: "Fumigation", icon: ShieldCheck, tone: "bg-card" },
  { to: "/services", label: "Pest Control", icon: Bug, tone: "bg-card" },
  { to: "/services", label: "Water Leakage Detection", icon: Droplets, tone: "bg-card" },
  { to: "/dashboard", label: "My Reports", icon: FileText, tone: "bg-card" },
  { to: "/dashboard", label: "My Bookings", icon: ClipboardList, tone: "bg-card" },
  { to: "/dashboard", label: "My Service History", icon: History, tone: "bg-card" },
  { to: "/providers", label: "Find Service Providers", icon: Building2, tone: "bg-card" },
  { to: "/learn", label: "Mold Education Center", icon: BookOpen, tone: "bg-card" },
] as const;

function Index() {
  const [stage, setStage] = useState<"splash" | "onboarding" | "home">("home");
  const [step, setStep] = useState(0);
  const { settings } = useAppSettings();
  const paid = scanRequiresPayment(settings);

  useEffect(() => {
    const seen = localStorage.getItem("emma-onboarded");
    setStage("splash");
    const timer = setTimeout(() => setStage(seen ? "home" : "onboarding"), 1700);
    return () => clearTimeout(timer);
  }, []);

  const { data: services } = useQuery({
    queryKey: ["services", "featured"],
    queryFn: async () => {
      const { data, error } = await supabase
        .from("services")
        .select("slug,name,short_description")
        .order("sort_order")
        .limit(4);
      if (error) throw error;
      return data;
    },
  });

  if (stage === "splash") {
    return (
      <div className="flex min-h-screen flex-col items-center justify-center bg-soft px-6 text-center">
        <div className="animate-in fade-in zoom-in-95 duration-700">
          <BrandMark className="mx-auto h-24 w-24" />
          <h1 className="mt-5 text-2xl font-bold">Emma Mold Inspection Services</h1>
          <p className="mt-2 text-sm font-medium text-primary">Protecting Homes from Mold</p>
          <p className="mt-1 text-xs text-muted-foreground">
            Professional Inspection • Cleaning • Fumigation
          </p>
        </div>
      </div>
    );
  }

  if (stage === "onboarding") {
    const current = onboarding[step];
    const last = step === onboarding.length - 1;
    return (
      <div className="flex min-h-screen flex-col justify-between bg-soft px-6 py-10">
        <div className="flex justify-end">
          <button
            className="text-xs font-semibold text-muted-foreground"
            onClick={() => {
              localStorage.setItem("emma-onboarded", "1");
              setStage("home");
            }}
          >
            Skip
          </button>
        </div>
        <div className="mx-auto w-full max-w-md text-center">
          <img
            src={heroImage}
            alt="AI scanning a home wall for mold"
            width={1200}
            height={900}
            className="mx-auto w-full rounded-3xl shadow-float"
          />
          <h2 className="mt-8 text-2xl font-bold">{current.title}</h2>
          <p className="mt-3 text-sm leading-relaxed text-muted-foreground">{current.text}</p>
          <div className="mt-6 flex justify-center gap-2">
            {onboarding.map((_, i) => (
              <span
                key={i}
                className={`h-1.5 rounded-full transition-all ${i === step ? "w-6 bg-primary" : "w-2 bg-border"}`}
              />
            ))}
          </div>
        </div>
        <button
          className="mx-auto w-full max-w-md rounded-2xl bg-brand py-4 text-sm font-semibold text-primary-foreground shadow-float"
          onClick={() => {
            if (last) {
              localStorage.setItem("emma-onboarded", "1");
              setStage("home");
            } else {
              setStep((s) => s + 1);
            }
          }}
        >
          {last ? "Get Started" : "Next"}
        </button>
      </div>
    );
  }

  return (
    <AppShell>
      <section className="overflow-hidden rounded-3xl bg-soft p-5 shadow-card">
        <p className="text-xs font-semibold uppercase tracking-widest text-primary">Inspect • Treat • Protect</p>
        <h1 className="mt-2 text-2xl font-bold leading-tight">Breathe better in a mold-free home</h1>
        <p className="mt-2 text-sm text-muted-foreground">
          Snap a photo for an AI-assisted preliminary check, then book certified inspection and treatment.
        </p>
        <img
          src={heroImage}
          alt="Bright clean room with an AI scan overlay"
          width={1200}
          height={900}
          className="mt-4 w-full rounded-2xl"
        />
        <Link
          to="/check"
          className="mt-4 flex items-center justify-center gap-2 rounded-2xl bg-brand py-3.5 text-sm font-semibold text-primary-foreground shadow-float"
        >
          <ScanLine className="h-4 w-4" />{" "}
          {paid ? `Check for Mold — ₦${settings.ai_scan_price_ngn.toLocaleString()}` : "Check for Mold — Free for now"}
        </Link>
      </section>

      <section className="mt-6">
        <h2 className="text-base font-semibold">What do you need?</h2>
        <div className="mt-3 grid grid-cols-2 gap-3">
          {actions.map((action) => {
            const Icon = action.icon;
            return (
              <Link
                key={action.label}
                to={action.to}
                className={`rounded-2xl border border-border/60 p-4 shadow-card transition-transform active:scale-[0.98] ${action.tone}`}
              >
                <Icon className="h-5 w-5" aria-hidden />
                <span className="mt-3 block text-sm font-semibold">{action.label}</span>
              </Link>
            );
          })}
        </div>
      </section>

      <section className="mt-8">
        <div className="flex items-center justify-between">
          <h2 className="text-base font-semibold">Popular services</h2>
          <Link to="/services" className="flex items-center gap-1 text-xs font-semibold text-primary">
            All services <ArrowRight className="h-3 w-3" />
          </Link>
        </div>
        <div className="mt-3 space-y-3">
          {services?.map((service) => (
            <Link
              key={service.slug}
              to="/services/$slug"
              params={{ slug: service.slug }}
              className="block rounded-2xl border border-border/60 bg-card p-4 shadow-card"
            >
              <span className="text-sm font-semibold">{service.name}</span>
              <p className="mt-1 text-xs text-muted-foreground">{service.short_description}</p>
            </Link>
          ))}
        </div>
      </section>

      <p className="mt-8 rounded-2xl bg-muted p-4 text-[11px] leading-relaxed text-muted-foreground">
        AI photo checks are a preliminary visual assessment and do not replace a professional mold inspection.
      </p>
    </AppShell>
  );
}
