import { useEffect, useState } from "react";
import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
import { toast } from "sonner";
import { supabase } from "@/integrations/supabase/client";
import { useAuth } from "@/hooks/useAuth";
import { SiteHeader } from "@/components/site-chrome";
import { Chip } from "@/components/chip";
import { createRecommendation } from "@/lib/imisi.functions";
import { FREE_RECOMMENDATIONS, OCCASIONS, TIMES_OF_DAY, WEATHER } from "@/lib/imisi";

export const Route = createFileRoute("/style")({
  head: () => ({
    meta: [
      { title: "Request a styling — Imisi" },
      {
        name: "description",
        content: "Tell Imisi the occasion, weather and setting, and receive a complete, explained look.",
      },
      { property: "og:title", content: "Request a styling — Imisi" },
      { property: "og:description", content: "A complete look, reasoned for your body, colouring and the impression you want." },
    ],
  }),
  component: StylePage,
});

function StylePage() {
  const navigate = useNavigate();
  const { session, loading } = useAuth();
  const [occasion, setOccasion] = useState("");
  const [customOccasion, setCustomOccasion] = useState("");
  const [weather, setWeather] = useState("");
  const [timeOfDay, setTimeOfDay] = useState("");
  const [location, setLocation] = useState("");
  const [dressCode, setDressCode] = useState("");
  const [notes, setNotes] = useState("");
  const [wantsHair, setWantsHair] = useState(false);
  const [wantsMakeup, setWantsMakeup] = useState(false);
  const [working, setWorking] = useState(false);

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

  const { data: profile } = useQuery({
    queryKey: ["profile", session?.user.id],
    enabled: !!session,
    queryFn: async () => {
      const { data, error } = await supabase
        .from("profiles")
        .select("*")
        .eq("id", session!.user.id)
        .maybeSingle();
      if (error) throw error;
      return data;
    },
  });

  useEffect(() => {
    if (profile && !profile.onboarding_complete) navigate({ to: "/onboarding" });
  }, [profile, navigate]);

  const used = profile?.recommendations_used ?? 0;
  const remaining = Math.max(0, FREE_RECOMMENDATIONS - used);
  const chosenOccasion = occasion === "Something else" ? customOccasion : occasion;

  const submit = async () => {
    if (!chosenOccasion.trim()) return;
    setWorking(true);
    try {
      const result = await createRecommendation({
        data: {
          occasion: chosenOccasion.trim(),
          weather: weather || null,
          timeOfDay: timeOfDay || null,
          location: location || null,
          dressCode: dressCode || null,
          notes: notes || null,
          wantsHair,
          wantsMakeup,
        },
      });
      navigate({ to: "/look/$id", params: { id: result.id } });
    } catch (error) {
      toast.error(error instanceof Error ? error.message : "That styling didn't complete.");
      setWorking(false);
    }
  };

  if (working) {
    return (
      <div className="min-h-screen">
        <SiteHeader />
        <div className="mx-auto flex max-w-xl flex-col items-center px-5 py-28 text-center">
          <div className="h-16 w-16 animate-spin rounded-full border-2 border-border border-t-clay" />
          <h1 className="mt-10 text-3xl">Styling you now…</h1>
          <p className="mt-4 text-sm leading-relaxed text-muted-foreground">
            I'm weighing your body shape and proportions, your skin tone and undertone, the impression
            you want to create, and what this occasion truly calls for — then building one complete look.
          </p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen">
      <SiteHeader />
      <main className="mx-auto max-w-3xl px-5 py-12">
        <p className="eyebrow">Styling session</p>
        <h1 className="mt-4 text-4xl md:text-5xl">
          {profile?.display_name ? `Where are we going, ${profile.display_name.split(" ")[0]}?` : "Where are we going?"}
        </h1>
        <p className="mt-3 text-sm text-muted-foreground">
          {remaining > 0
            ? `${remaining} of your ${FREE_RECOMMENDATIONS} free styling sessions remaining.`
            : "You've used all 3 free sessions."}
        </p>

        {remaining === 0 ? (
          <div className="paper mt-10 p-9">
            <h2 className="text-2xl">Your free sessions are complete</h2>
            <p className="mt-3 text-sm text-muted-foreground">
              Every look you've already received stays yours to revisit. Unlimited styling arrives with
              Imisi Premium.
            </p>
            <div className="mt-7 flex flex-wrap gap-3">
              <Link to="/premium" className="rounded-md bg-clay px-7 py-3.5 text-sm font-medium text-clay-foreground">
                Join the waitlist
              </Link>
              <Link
                to="/saved"
                className="rounded-md border border-input px-7 py-3.5 text-sm font-medium transition-colors hover:bg-secondary"
              >
                View my looks
              </Link>
            </div>
          </div>
        ) : (
          <div className="mt-10 space-y-10">
            <Field label="The occasion">
              <div className="flex flex-wrap gap-3">
                {[...OCCASIONS, "Something else"].map((o) => (
                  <Chip key={o} selected={occasion === o} onClick={() => setOccasion(o)}>
                    {o}
                  </Chip>
                ))}
              </div>
              {occasion === "Something else" && (
                <input
                  value={customOccasion}
                  onChange={(e) => setCustomOccasion(e.target.value)}
                  placeholder="Tell me the occasion"
                  className="mt-4 w-full max-w-md rounded-md border border-input bg-card px-4 py-3 text-sm outline-none focus:border-clay"
                />
              )}
            </Field>

            <Field label="Weather">
              <div className="flex flex-wrap gap-3">
                {WEATHER.map((w) => (
                  <Chip key={w} selected={weather === w} onClick={() => setWeather(w)}>
                    {w}
                  </Chip>
                ))}
              </div>
            </Field>

            <Field label="Time of day">
              <div className="flex flex-wrap gap-3">
                {TIMES_OF_DAY.map((t) => (
                  <Chip key={t} selected={timeOfDay === t} onClick={() => setTimeOfDay(t)}>
                    {t}
                  </Chip>
                ))}
              </div>
            </Field>

            <div className="grid gap-6 sm:grid-cols-2">
              <Field label="Location">
                <input
                  value={location}
                  onChange={(e) => setLocation(e.target.value)}
                  placeholder="Lagos, Ikoyi"
                  className="w-full rounded-md border border-input bg-card px-4 py-3 text-sm outline-none focus:border-clay"
                />
              </Field>
              <Field label="Dress code (if any)">
                <input
                  value={dressCode}
                  onChange={(e) => setDressCode(e.target.value)}
                  placeholder="Strictly traditional, black tie…"
                  className="w-full rounded-md border border-input bg-card px-4 py-3 text-sm outline-none focus:border-clay"
                />
              </Field>
            </div>

            <Field label="Anything else I should know?">
              <textarea
                value={notes}
                onChange={(e) => setNotes(e.target.value)}
                rows={3}
                maxLength={600}
                placeholder="I'll be on my feet all evening, and I'd rather not show my arms."
                className="w-full rounded-md border border-input bg-card px-4 py-3 text-sm outline-none focus:border-clay"
              />
            </Field>

            <Field label="Include">
              <div className="flex flex-wrap gap-3">
                <Chip selected={wantsHair} onClick={() => setWantsHair((v) => !v)}>
                  Hair direction
                </Chip>
                <Chip selected={wantsMakeup} onClick={() => setWantsMakeup((v) => !v)}>
                  Makeup direction
                </Chip>
              </div>
            </Field>

            <button
              onClick={submit}
              disabled={!chosenOccasion.trim()}
              className="rounded-md bg-clay px-8 py-4 text-sm font-medium text-clay-foreground transition-opacity hover:opacity-90 disabled:opacity-40"
            >
              Style me
            </button>
          </div>
        )}
      </main>
    </div>
  );
}

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