import { useEffect } from "react";
import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { supabase } from "@/integrations/supabase/client";
import { useAuth } from "@/hooks/useAuth";
import { SiteFooter, SiteHeader } from "@/components/site-chrome";
import { PREMIUM_FEATURES, type LookPayload } from "@/lib/imisi";

export const Route = createFileRoute("/look/$id")({
  head: () => ({
    meta: [
      { title: "Your Imisi consultation" },
      {
        name: "description",
        content: "A complete look with colour analysis, fit analysis, perception analysis and styling tips.",
      },
      { property: "og:title", content: "Your Imisi consultation" },
      { property: "og:description", content: "A complete look, reasoned for you by your AI personal image consultant." },
    ],
  }),
  component: LookPage,
});

function LookPage() {
  const { id } = Route.useParams();
  const navigate = useNavigate();
  const { session, loading } = useAuth();
  const queryClient = useQueryClient();

  useEffect(() => {
    if (!loading && !session) navigate({ to: "/auth" });
  }, [loading, session, navigate]);

  const { data, isLoading } = useQuery({
    queryKey: ["look", id],
    enabled: !!session,
    queryFn: async () => {
      const { data: row, error } = await supabase
        .from("recommendations")
        .select("*")
        .eq("id", id)
        .maybeSingle();
      if (error) throw error;
      if (!row) return null;
      let imageUrl: string | null = null;
      if (row.image_path) {
        const { data: signed } = await supabase.storage
          .from("user-photos")
          .createSignedUrl(row.image_path, 60 * 60);
        imageUrl = signed?.signedUrl ?? null;
      }
      return { row, imageUrl, look: row.payload as unknown as LookPayload };
    },
  });

  const save = useMutation({
    mutationFn: async (next: boolean) => {
      const { error } = await supabase.from("recommendations").update({ saved: next }).eq("id", id);
      if (error) throw error;
      return next;
    },
    onSuccess: (next) => {
      queryClient.invalidateQueries({ queryKey: ["look", id] });
      queryClient.invalidateQueries({ queryKey: ["looks"] });
      toast.success(next ? "Saved to your looks." : "Removed from saved looks.");
    },
    onError: () => toast.error("Could not update this look."),
  });

  if (isLoading || !data) {
    return (
      <div className="min-h-screen">
        <SiteHeader />
        <div className="mx-auto max-w-3xl px-5 py-24 text-center text-sm text-muted-foreground">
          {isLoading ? "Opening your consultation…" : "This look could not be found."}
        </div>
      </div>
    );
  }

  const { row, imageUrl, look } = data;

  return (
    <div className="min-h-screen">
      <SiteHeader />
      <main className="mx-auto max-w-5xl px-5 py-12">
        <p className="eyebrow">
          {row.occasion}
          {row.location ? ` · ${row.location}` : ""}
          {row.time_of_day ? ` · ${row.time_of_day}` : ""}
        </p>
        <h1 className="mt-4 max-w-3xl text-4xl md:text-5xl">{look.title}</h1>
        <p className="mt-5 max-w-2xl text-base leading-relaxed text-muted-foreground">{look.opening}</p>

        <div className="mt-10 grid gap-10 md:grid-cols-[minmax(0,0.9fr)_minmax(0,1.1fr)]">
          <div>
            {imageUrl ? (
              <img
                src={imageUrl}
                alt={`Visualisation of ${look.title}`}
                loading="lazy"
                className="w-full rounded-2xl border border-border object-cover shadow-lift"
              />
            ) : (
              <div className="paper flex aspect-[3/4] items-center justify-center p-8 text-center text-sm text-muted-foreground">
                The visualisation didn't render for this look — the full consultation below still applies.
              </div>
            )}
            <button
              onClick={() => save.mutate(!row.saved)}
              className={`mt-5 w-full rounded-md px-6 py-3.5 text-sm font-medium transition-colors ${
                row.saved
                  ? "border border-clay text-clay hover:bg-clay hover:text-clay-foreground"
                  : "bg-clay text-clay-foreground hover:opacity-90"
              }`}
            >
              {row.saved ? "Saved to your looks" : "Save this look"}
            </button>
          </div>

          <div className="space-y-10">
            <Block title="The look">
              <div className="divide-y divide-border">
                {look.outfit?.map((item) => (
                  <ItemRow key={item.item + item.description} {...item} />
                ))}
              </div>
            </Block>

            {look.shoes && (
              <Block title="Shoes">
                <ItemRow {...look.shoes} />
              </Block>
            )}

            {look.accessories?.length > 0 && (
              <Block title="Accessories">
                <div className="divide-y divide-border">
                  {look.accessories.map((item) => (
                    <ItemRow key={item.item + item.description} {...item} />
                  ))}
                </div>
              </Block>
            )}

            {look.hair && <Block title="Hair"><p className="text-sm leading-relaxed">{look.hair}</p></Block>}
            {look.makeup && <Block title="Makeup"><p className="text-sm leading-relaxed">{look.makeup}</p></Block>}
          </div>
        </div>

        <div className="mt-14 grid gap-6 md:grid-cols-2">
          <Panel title="Colour analysis" body={look.color_analysis} />
          <Panel title="Fit analysis" body={look.fit_analysis} />
        </div>

        {look.why_this_works?.length > 0 && (
          <div className="paper mt-6 p-8">
            <h2 className="text-2xl">Why this works for you</h2>
            <ul className="mt-5 grid gap-3 sm:grid-cols-2">
              {look.why_this_works.map((w) => (
                <li key={w} className="flex gap-2 text-sm leading-relaxed text-muted-foreground">
                  <span className="text-gold">◆</span>
                  {w}
                </li>
              ))}
            </ul>
          </div>
        )}

        <div className="mt-6 grid gap-6 md:grid-cols-2">
          <Panel title="How you'll be perceived" body={look.perception_analysis} />
          {look.styling_tips?.length > 0 && (
            <div className="paper p-8">
              <h2 className="text-2xl">Styling tips</h2>
              <ul className="mt-5 space-y-3">
                {look.styling_tips.map((t) => (
                  <li key={t} className="flex gap-2 text-sm leading-relaxed text-muted-foreground">
                    <span className="text-gold">◆</span>
                    {t}
                  </li>
                ))}
              </ul>
            </div>
          )}
        </div>

        <div className="paper mt-10 p-9">
          <p className="eyebrow">Locked — Imisi Premium</p>
          <h2 className="mt-3 text-2xl">Take this further</h2>
          <ul className="mt-5 grid gap-2 text-sm text-muted-foreground sm:grid-cols-2">
            {PREMIUM_FEATURES.slice(0, 6).map((f) => (
              <li key={f} className="flex gap-2 opacity-70">
                <span>🔒</span>
                {f}
              </li>
            ))}
          </ul>
          <Link
            to="/premium"
            className="mt-7 inline-block rounded-md border border-clay px-6 py-3 text-sm font-medium text-clay transition-colors hover:bg-clay hover:text-clay-foreground"
          >
            Coming soon — join the waitlist
          </Link>
        </div>
      </main>
      <SiteFooter />
    </div>
  );
}

function Block({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <section>
      <p className="eyebrow mb-4">{title}</p>
      {children}
    </section>
  );
}

function ItemRow({ item, description, why }: { item: string; description: string; why: string }) {
  return (
    <div className="py-5 first:pt-0">
      <p className="text-xs uppercase tracking-widest text-muted-foreground">{item}</p>
      <p className="mt-1.5 text-lg">{description}</p>
      <p className="mt-2 text-sm leading-relaxed text-muted-foreground">{why}</p>
    </div>
  );
}

function Panel({ title, body }: { title: string; body?: string }) {
  if (!body) return null;
  return (
    <div className="paper p-8">
      <h2 className="text-2xl">{title}</h2>
      <p className="mt-4 text-sm leading-relaxed text-muted-foreground">{body}</p>
    </div>
  );
}
