"use client";

import { useState, type FormEvent } from "react";
import { useRouter } from "next/navigation";
import type { AuthUser } from "@/types/user";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { useToast } from "@/components/ui/toast";
import { clientFetch } from "@/lib/api/client";

export function CompleteProfileForm({ user }: { user: AuthUser }) {
  const router = useRouter();
  const [phone, setPhone] = useState(user.phone ?? "");
  const [dateOfBirth, setDateOfBirth] = useState(user.date_of_birth ?? "");
  const [error, setError] = useState<string | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const { toast } = useToast();

  async function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setError(null);
    setIsSubmitting(true);

    const res = await clientFetch("/api/profile", {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ name: user.name, phone, date_of_birth: dateOfBirth }),
    });

    const body = await res.json().catch(() => null);

    if (!res.ok) {
      const message = body?.message ?? "Failed to save profile. Please try again.";
      setError(message);
      toast(message, "error");
      setIsSubmitting(false);
      return;
    }

    router.push("/");
    router.refresh();
  }

  return (
    <form onSubmit={handleSubmit} className="mt-8 flex flex-col gap-4">
      {user.avatar_url && (
        // eslint-disable-next-line @next/next/no-img-element -- Google-provided URL, not on next/image allowlist
        <img src={user.avatar_url} alt="" className="h-16 w-16 self-center rounded-full" />
      )}

      <label className="flex flex-col gap-1 text-sm font-medium">
        Full Name
        <input
          disabled
          value={user.name}
          className="rounded-lg border border-kolabora-neutral-dark/10 bg-kolabora-neutral-dark/5 px-3 py-2 text-base font-normal text-kolabora-neutral-dark/70"
        />
      </label>

      <label className="flex flex-col gap-1 text-sm font-medium">
        Email
        <input
          disabled
          value={user.email}
          className="rounded-lg border border-kolabora-neutral-dark/10 bg-kolabora-neutral-dark/5 px-3 py-2 text-base font-normal text-kolabora-neutral-dark/70"
        />
      </label>

      <label className="flex flex-col gap-1 text-sm font-medium">
        Phone Number
        <Input type="tel" required value={phone} onChange={(e) => setPhone(e.target.value)} />
      </label>

      <label className="flex flex-col gap-1 text-sm font-medium">
        Date of Birth
        <Input
          type="date"
          required
          value={dateOfBirth}
          onChange={(e) => setDateOfBirth(e.target.value)}
        />
      </label>

      {error && <p className="text-sm text-red-600">{error}</p>}

      <Button type="submit" loading={isSubmitting} className="mt-2">
        Save & Continue
      </Button>
    </form>
  );
}
