import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";
import { useEffect, useState } from "react";
import { useAuth } from "@/hooks/use-auth";
import { supabase } from "@/integrations/supabase/client";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Badge } from "@/components/ui/badge";
import { toast } from "sonner";
import { ArrowLeft } from "lucide-react";

export const Route = createFileRoute("/_authenticated/profile")({
  head: () => ({ meta: [{ title: "My profile · SkillKonnect" }] }),
  component: ProfilePage,
});

type ProfileRow = {
  full_name: string | null;
  phone: string | null;
  organization: string | null;
  bio: string | null;
  avatar_url: string | null;
  status: "pending" | "active" | "suspended";
};

function ProfilePage() {
  const { user, roles } = useAuth();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [status, setStatus] = useState<ProfileRow["status"]>("pending");
  const [form, setForm] = useState({
    full_name: "",
    phone: "",
    organization: "",
    bio: "",
    avatar_url: "",
  });

  useEffect(() => {
    if (!user) return;
    (async () => {
      const { data } = await supabase
        .from("profiles")
        .select("full_name, phone, organization, bio, avatar_url, status")
        .eq("id", user.id)
        .maybeSingle();
      if (data) {
        const p = data as ProfileRow;
        setStatus(p.status);
        setForm({
          full_name: p.full_name ?? "",
          phone: p.phone ?? "",
          organization: p.organization ?? "",
          bio: p.bio ?? "",
          avatar_url: p.avatar_url ?? "",
        });
      }
      setLoading(false);
    })();
  }, [user]);

  async function onSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!user) return;
    if (!form.full_name.trim()) {
      toast.error("Please enter your full name");
      return;
    }
    setSaving(true);
    try {
      const { error } = await supabase
        .from("profiles")
        .upsert(
          {
            id: user.id,
            full_name: form.full_name.trim(),
            phone: form.phone.trim() || null,
            organization: form.organization.trim() || null,
            bio: form.bio.trim() || null,
            avatar_url: form.avatar_url.trim() || null,
          },
          { onConflict: "id" },
        );
      if (error) throw error;
      toast.success("Profile saved");
      navigate({ to: "/dashboard" });
    } catch (err) {
      const message = err instanceof Error ? err.message : "Could not save profile";
      toast.error(message);
    } finally {
      setSaving(false);
    }
  }


  const isTrainer = roles.includes("trainer");

  return (
    <div className="min-h-screen bg-background">
      <header className="sticky top-0 z-30 backdrop-blur bg-background/80 border-b border-border/60">
        <div className="container-prose flex h-16 items-center">
          <Button variant="ghost" size="sm" asChild className="gap-1.5">
            <Link to="/dashboard"><ArrowLeft className="h-4 w-4" /> Dashboard</Link>
          </Button>
        </div>
      </header>

      <main className="container-prose py-8 max-w-2xl">
        <Card className="border-border/60">
          <CardHeader>
            <div className="flex items-center justify-between gap-3">
              <div>
                <CardTitle>My profile</CardTitle>
                <CardDescription>
                  {isTrainer
                    ? "Complete your profile to be discoverable by schools."
                    : "Keep your organization details up to date."}
                </CardDescription>
              </div>
              {isTrainer && (
                <Badge variant={status === "active" ? "default" : "secondary"} className="capitalize">
                  {status}
                </Badge>
              )}
            </div>
          </CardHeader>
          <CardContent>
            {loading ? (
              <p className="text-sm text-muted-foreground">Loading…</p>
            ) : (
              <form onSubmit={onSubmit} className="space-y-4">
                <div className="space-y-1.5">
                  <Label htmlFor="full_name">Full name</Label>
                  <Input id="full_name" required maxLength={120}
                    value={form.full_name}
                    onChange={(e) => setForm({ ...form, full_name: e.target.value })} />
                </div>
                <div className="space-y-1.5">
                  <Label htmlFor="organization">{isTrainer ? "Trade / specialty" : "Organization"}</Label>
                  <Input id="organization" maxLength={160}
                    placeholder={isTrainer ? "e.g. Welding, Solar PVC" : "School name"}
                    value={form.organization}
                    onChange={(e) => setForm({ ...form, organization: e.target.value })} />
                </div>
                <div className="space-y-1.5">
                  <Label htmlFor="phone">Phone</Label>
                  <Input id="phone" type="tel" maxLength={32}
                    value={form.phone}
                    onChange={(e) => setForm({ ...form, phone: e.target.value })} />
                </div>
                <div className="space-y-1.5">
                  <Label htmlFor="avatar_url">Avatar URL</Label>
                  <Input id="avatar_url" type="url" maxLength={500}
                    placeholder="https://…"
                    value={form.avatar_url}
                    onChange={(e) => setForm({ ...form, avatar_url: e.target.value })} />
                </div>
                <div className="space-y-1.5">
                  <Label htmlFor="bio">{isTrainer ? "About you & experience" : "About"}</Label>
                  <Textarea id="bio" rows={5} maxLength={2000}
                    placeholder={isTrainer ? "Years of experience, certifications, trades you teach…" : "About your school"}
                    value={form.bio}
                    onChange={(e) => setForm({ ...form, bio: e.target.value })} />
                </div>
                <Button type="submit" disabled={saving} className="w-full">
                  {saving ? "Saving…" : "Save profile"}
                </Button>
              </form>
            )}
          </CardContent>
        </Card>
      </main>
    </div>
  );
}
