import { createFileRoute } from "@tanstack/react-router";
import { useEffect, useState } from "react";
import { toast } from "sonner";
import { z } from "zod";
import { Loader2 } from "lucide-react";

import { supabase } from "@/integrations/supabase/client";
import { PortalShell } from "@/components/portal/PortalShell";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Skeleton } from "@/components/ui/skeleton";

export const Route = createFileRoute("/_authenticated/profile")({
  head: () => ({
    meta: [
      { title: "My Profile — Flexflares Cyber Services" },
      { name: "description", content: "Update your name, phone, WhatsApp number and account password." },
      { property: "og:title", content: "My Profile — Flexflares Cyber Services" },
      { property: "og:description", content: "Manage your Flexflares account details." },
    ],
  }),
  component: ProfilePage,
});

const profileSchema = z.object({
  full_name: z.string().trim().min(2, "Enter your full name").max(100),
  username: z.string().trim().min(3, "Username must be 3+ characters").max(30),
  phone: z.string().trim().min(7, "Enter a valid phone number").max(20),
});

function ProfilePage() {
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [email, setEmail] = useState("");
  const [profile, setProfile] = useState({ full_name: "", username: "", phone: "", referral_code: "" });

  useEffect(() => {
    (async () => {
      const { data: u } = await supabase.auth.getUser();
      if (!u.user) return;
      setEmail(u.user.email ?? "");
      const { data } = await supabase
        .from("profiles")
        .select("full_name, username, phone, referral_code")
        .eq("id", u.user.id)
        .maybeSingle();
      if (data) {
        setProfile({
          full_name: data.full_name ?? "",
          username: data.username ?? "",
          phone: data.phone ?? "",
          referral_code: data.referral_code ?? "",
        });
      }
      setLoading(false);
    })();
  }, []);

  const save = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const parsed = profileSchema.safeParse(profile);
    if (!parsed.success) return toast.error(parsed.error.issues[0]?.message ?? "Please check the form");
    const { data: u } = await supabase.auth.getUser();
    if (!u.user) return;
    setSaving(true);
    const { error } = await supabase.from("profiles").update(parsed.data).eq("id", u.user.id);
    setSaving(false);
    if (error) return toast.error(error.message);
    toast.success("Profile updated");
  };

  const changePassword = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const fd = new FormData(e.currentTarget);
    const password = String(fd.get("password") ?? "");
    const confirm = String(fd.get("confirm") ?? "");
    if (password.length < 6) return toast.error("Password must be 6+ characters");
    if (password !== confirm) return toast.error("Passwords do not match");
    const { error } = await supabase.auth.updateUser({ password });
    if (error) return toast.error(error.message);
    toast.success("Password changed");
    e.currentTarget.reset();
  };

  return (
    <PortalShell title="My profile" description="Keep your contact details up to date so we can reach you fast.">
      {loading ? (
        <Skeleton className="h-80 w-full rounded-xl" />
      ) : (
        <div className="grid gap-4 lg:grid-cols-2">
          <Card className="glass">
            <CardContent className="p-6">
              <h2 className="text-lg font-semibold">Account details</h2>
              <form onSubmit={save} className="mt-4 space-y-4">
                <div>
                  <Label htmlFor="full_name">Full name</Label>
                  <Input
                    id="full_name"
                    value={profile.full_name}
                    onChange={(e) => setProfile((s) => ({ ...s, full_name: e.target.value }))}
                    className="mt-1"
                  />
                </div>
                <div>
                  <Label htmlFor="username">Username</Label>
                  <Input
                    id="username"
                    value={profile.username}
                    onChange={(e) => setProfile((s) => ({ ...s, username: e.target.value }))}
                    className="mt-1"
                  />
                </div>
                <div>
                  <Label htmlFor="phone">Phone / WhatsApp</Label>
                  <Input
                    id="phone"
                    type="tel"
                    value={profile.phone}
                    onChange={(e) => setProfile((s) => ({ ...s, phone: e.target.value }))}
                    className="mt-1"
                  />
                </div>
                <div>
                  <Label htmlFor="email">Email</Label>
                  <Input id="email" value={email} readOnly disabled className="mt-1" />
                </div>
                {profile.referral_code && (
                  <p className="text-xs text-muted-foreground">
                    Your referral code: <span className="font-semibold text-primary">{profile.referral_code}</span>
                  </p>
                )}
                <Button type="submit" disabled={saving}>
                  {saving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                  Save changes
                </Button>
              </form>
            </CardContent>
          </Card>

          <Card className="glass">
            <CardContent className="p-6">
              <h2 className="text-lg font-semibold">Change password</h2>
              <form onSubmit={changePassword} className="mt-4 space-y-4">
                <div>
                  <Label htmlFor="password">New password</Label>
                  <Input id="password" name="password" type="password" autoComplete="new-password" className="mt-1" />
                </div>
                <div>
                  <Label htmlFor="confirm">Confirm new password</Label>
                  <Input id="confirm" name="confirm" type="password" autoComplete="new-password" className="mt-1" />
                </div>
                <Button type="submit" variant="outline">
                  Update password
                </Button>
              </form>
            </CardContent>
          </Card>
        </div>
      )}
    </PortalShell>
  );
}