"use client";

import Link from "next/link";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { Button, useToast } from "@/components/ui";
import { api } from "@/lib/api-client";

export function LoginForm({ initialError }: { initialError?: string }) {
  const router = useRouter();
  const { toast, toastNode } = useToast();
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [busy, setBusy] = useState(false);

  const submit = async () => {
    setBusy(true);
    try {
      await api("/api/auth/login", { method: "POST", json: { email, password } });
      toast("Welcome back");
      router.push("/");
      router.refresh();
    } catch (error) {
      toast(error instanceof Error ? error.message : "Login failed");
    } finally {
      setBusy(false);
    }
  };

  return (
    <div className="mx-auto max-w-sm space-y-4 px-4 py-12">
      <h1 className="text-2xl font-bold">Sign in to PlayTube</h1>
      {initialError ? <p className="rounded-lg bg-red-500/10 p-3 text-sm text-red-500">{initialError}</p> : null}
      <input value={email} onChange={(event) => setEmail(event.target.value)} type="email" placeholder="Email" className="w-full rounded-lg border border-line bg-surface px-3 py-2.5 text-sm" />
      <input value={password} onChange={(event) => setPassword(event.target.value)} type="password" placeholder="Password" className="w-full rounded-lg border border-line bg-surface px-3 py-2.5 text-sm" />
      <Button className="w-full" onClick={() => void submit()} disabled={busy}>{busy ? "Signing in..." : "Sign in"}</Button>
      <a href="/api/auth/google" className="flex w-full items-center justify-center gap-2 rounded-full border border-line px-4 py-2.5 text-sm font-medium hover:bg-surface">
        <span aria-hidden>🇬</span> Continue with Google
      </a>
      <p className="text-sm text-muted">
        No account? <Link href="/signup" className="font-semibold text-brand">Create one</Link>
      </p>
      <p className="text-sm text-muted">
        <Link href="/forgot-password" className="font-semibold text-brand">Forgot password?</Link>
      </p>
      <div className="rounded-lg bg-surface p-3 text-xs text-muted">
        <p className="font-semibold text-fg">Demo accounts</p>
        <p>viewer@playtube.dev / Studio123!</p>
        <p>studio@playtube.dev / Studio123!</p>
        <p>admin@playtube.dev / Admin123!</p>
      </div>
      {toastNode}
    </div>
  );
}

export function SignupForm() {
  const router = useRouter();
  const { toast, toastNode } = useToast();
  const [form, setForm] = useState({ email: "", password: "", displayName: "", channelName: "" });
  const [verifyUrl, setVerifyUrl] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);

  const submit = async () => {
    setBusy(true);
    try {
      const data = await api<{ verifyUrl: string | null }>("/api/auth/signup", { method: "POST", json: form });
      if (data.verifyUrl) setVerifyUrl(data.verifyUrl);
      else {
        toast("Account created — welcome to PlayTube");
        router.push("/");
        router.refresh();
      }
    } catch (error) {
      toast(error instanceof Error ? error.message : "Sign up failed");
    } finally {
      setBusy(false);
    }
  };

  return (
    <div className="mx-auto max-w-sm space-y-4 px-4 py-12">
      <h1 className="text-2xl font-bold">Create your PlayTube account</h1>
      {verifyUrl ? (
        <div className="rounded-lg bg-surface p-4 text-sm">
          <p className="font-semibold">Confirm your email</p>
          <p className="mt-1 text-muted">Email delivery is not configured on this deployment, so use the link below to verify your address.</p>
          <a href={verifyUrl} className="mt-2 inline-block font-semibold text-brand">Verify my email →</a>
        </div>
      ) : null}
      <input value={form.displayName} onChange={(event) => setForm({ ...form, displayName: event.target.value })} placeholder="Your name" className="w-full rounded-lg border border-line bg-surface px-3 py-2.5 text-sm" />
      <input value={form.channelName} onChange={(event) => setForm({ ...form, channelName: event.target.value })} placeholder="Channel name (optional)" className="w-full rounded-lg border border-line bg-surface px-3 py-2.5 text-sm" />
      <input value={form.email} onChange={(event) => setForm({ ...form, email: event.target.value })} type="email" placeholder="Email" className="w-full rounded-lg border border-line bg-surface px-3 py-2.5 text-sm" />
      <input value={form.password} onChange={(event) => setForm({ ...form, password: event.target.value })} type="password" placeholder="Password (min 8 characters)" className="w-full rounded-lg border border-line bg-surface px-3 py-2.5 text-sm" />
      <Button className="w-full" onClick={() => void submit()} disabled={busy}>{busy ? "Creating..." : "Create account"}</Button>
      <a href="/api/auth/google" className="flex w-full items-center justify-center gap-2 rounded-full border border-line px-4 py-2.5 text-sm font-medium hover:bg-surface">
        <span aria-hidden>🇬</span> Sign up with Google
      </a>
      <p className="text-sm text-muted">Already have an account? <Link href="/login" className="font-semibold text-brand">Sign in</Link></p>
      {toastNode}
    </div>
  );
}

export function ForgotForm() {
  const { toast, toastNode } = useToast();
  const [email, setEmail] = useState("");
  const [resetUrl, setResetUrl] = useState<string | null>(null);

  return (
    <div className="mx-auto max-w-sm space-y-4 px-4 py-12">
      <h1 className="text-2xl font-bold">Reset your password</h1>
      <p className="text-sm text-muted">We will send a reset link to your email address.</p>
      <input value={email} onChange={(event) => setEmail(event.target.value)} type="email" placeholder="Email" className="w-full rounded-lg border border-line bg-surface px-3 py-2.5 text-sm" />
      <Button
        className="w-full"
        onClick={async () => {
          const data = await api<{ resetUrl: string | null }>("/api/auth/forgot", { method: "POST", json: { email } }).catch((e) => {
            toast(e.message);
            return null;
          });
          if (data?.resetUrl) setResetUrl(data.resetUrl);
          else toast("If that account exists, a reset link is on its way");
        }}
      >
        Send reset link
      </Button>
      {resetUrl ? (
        <div className="rounded-lg bg-surface p-4 text-sm">
          <p className="font-semibold">Email delivery is not configured</p>
          <a href={resetUrl} className="mt-2 inline-block font-semibold text-brand">Open my reset link →</a>
        </div>
      ) : null}
      {toastNode}
    </div>
  );
}

export function ResetForm({ token }: { token: string }) {
  const router = useRouter();
  const { toast, toastNode } = useToast();
  const [password, setPassword] = useState("");

  return (
    <div className="mx-auto max-w-sm space-y-4 px-4 py-12">
      <h1 className="text-2xl font-bold">Choose a new password</h1>
      <input value={password} onChange={(event) => setPassword(event.target.value)} type="password" placeholder="New password" className="w-full rounded-lg border border-line bg-surface px-3 py-2.5 text-sm" />
      <Button
        className="w-full"
        onClick={async () => {
          await api("/api/auth/reset", { method: "POST", json: { token, password } }).catch((e) => toast(e.message));
          toast("Password updated — sign in with your new password");
          router.push("/login");
        }}
      >
        Update password
      </Button>
      {toastNode}
    </div>
  );
}
