import { useEffect, useState } from "react";
import { useNavigate, Link } from "react-router-dom";
import { supabase } from "@/integrations/supabase/client";
import { Button } from "@/components/ui/button";
import { UtensilsCrossed, LogOut, Sparkles } from "lucide-react";
import { toast } from "sonner";

interface Profile {
  full_name: string | null;
  restaurant_name: string | null;
}

const Dashboard = () => {
  const navigate = useNavigate();
  const [profile, setProfile] = useState<Profile | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let mounted = true;

    const { data: sub } = supabase.auth.onAuthStateChange((_e, session) => {
      if (!session) navigate("/auth?mode=login", { replace: true });
    });

    supabase.auth.getSession().then(async ({ data }) => {
      if (!data.session) {
        navigate("/auth?mode=login", { replace: true });
        return;
      }
      const { data: p } = await supabase
        .from("profiles")
        .select("full_name, restaurant_name")
        .eq("id", data.session.user.id)
        .maybeSingle();
      if (mounted) {
        setProfile(p);
        setLoading(false);
      }
    });

    return () => {
      mounted = false;
      sub.subscription.unsubscribe();
    };
  }, [navigate]);

  const handleLogout = async () => {
    await supabase.auth.signOut();
    toast.success("Signed out");
    navigate("/");
  };

  return (
    <div className="min-h-screen bg-gradient-subtle">
      <header className="border-b border-border bg-background/80 backdrop-blur">
        <div className="container flex h-16 items-center justify-between">
          <Link to="/" className="flex items-center gap-2">
            <div className="flex h-9 w-9 items-center justify-center rounded-xl bg-gradient-warm">
              <UtensilsCrossed className="h-5 w-5 text-primary-foreground" />
            </div>
            <span className="font-display text-xl font-semibold" style={{ fontFamily: 'var(--font-display)' }}>Sercé</span>
          </Link>
          <Button variant="ghost" size="sm" onClick={handleLogout}>
            <LogOut className="h-4 w-4" /> Sign out
          </Button>
        </div>
      </header>

      <main className="container py-12 md:py-20">
        {loading ? (
          <div className="text-muted-foreground">Loading…</div>
        ) : (
          <div className="max-w-3xl">
            <div className="inline-flex items-center gap-2 rounded-full border border-border bg-card px-4 py-1.5 text-sm text-muted-foreground shadow-soft">
              <Sparkles className="h-3.5 w-3.5 text-primary" />
              You're all set
            </div>
            <h1 className="text-4xl md:text-5xl font-semibold tracking-tight mt-6">
              Welcome{profile?.full_name ? `, ${profile.full_name.split(" ")[0]}` : ""} 👋
            </h1>
            <p className="text-lg text-muted-foreground mt-3">
              {profile?.restaurant_name
                ? <>Your space for <span className="text-foreground font-medium">{profile.restaurant_name}</span> is ready. Build your first digital menu next.</>
                : "Your account is ready. Build your first digital menu next."}
            </p>

            <div className="mt-10 grid sm:grid-cols-2 gap-4">
              <div className="rounded-2xl bg-card border border-border p-6 shadow-soft">
                <div className="text-sm font-semibold text-primary uppercase tracking-wider">Step 1</div>
                <h3 className="text-xl font-semibold mt-2">Create your first menu</h3>
                <p className="text-muted-foreground text-sm mt-2">Add categories, dishes, photos, and prices.</p>
                <Button variant="hero" className="mt-5" disabled>Coming soon</Button>
              </div>
              <div className="rounded-2xl bg-card border border-border p-6 shadow-soft">
                <div className="text-sm font-semibold text-primary uppercase tracking-wider">Step 2</div>
                <h3 className="text-xl font-semibold mt-2">Print your QR codes</h3>
                <p className="text-muted-foreground text-sm mt-2">Generate and download QR codes for every table.</p>
                <Button variant="soft" className="mt-5" disabled>Coming soon</Button>
              </div>
            </div>
          </div>
        )}
      </main>
    </div>
  );
};

export default Dashboard;
