"use client";

import { useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { User, Phone, Mail, Lock, AlertCircle } from "lucide-react";
import { AuthShell } from "@/components/auth/AuthShell";
import { TextField } from "@/components/ui/TextField";
import { Button } from "@/components/ui/Button";
import { apiPost, ApiError } from "@/lib/api/client";
import { useTranslation } from "@/lib/i18n/LanguageProvider";

export default function SignupPage() {
  const router = useRouter();
  const { t } = useTranslation();
  const [form, setForm] = useState({
    fullName: "",
    phone: "",
    email: "",
    password: "",
    confirmPassword: "",
  });
  const [agreed, setAgreed] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  function update<K extends keyof typeof form>(key: K, value: string) {
    setForm((f) => ({ ...f, [key]: value }));
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);

    if (!form.fullName.trim() || !form.phone.trim() || !form.email.trim()) {
      setError(t("signup.fillFields"));
      return;
    }
    if (form.password.length < 8) {
      setError(t("signup.passwordTooShort"));
      return;
    }
    if (form.password !== form.confirmPassword) {
      setError(t("signup.passwordMismatch"));
      return;
    }
    if (!agreed) {
      setError(t("signup.mustAgree"));
      return;
    }

    setLoading(true);
    try {
      await apiPost("/api/auth/signup", {
        email: form.email.trim(),
        password: form.password,
        fullName: form.fullName.trim(),
        phone: form.phone.trim(),
      });
      router.push(`/verify-email?email=${encodeURIComponent(form.email.trim())}`);
    } catch (err) {
      setError(
        err instanceof ApiError
          ? err.message.toLowerCase().includes("already exists")
            ? t("signup.alreadyRegistered")
            : err.message
          : t("common.genericError")
      );
    } finally {
      setLoading(false);
    }
  }

  return (
    <AuthShell
      title={t("signup.title")}
      subtitle={t("signup.subtitle")}
      backHref="/welcome"
    >
      <form onSubmit={handleSubmit} className="flex flex-col gap-4">
        <TextField
          label={t("signup.fullName")}
          autoComplete="name"
          icon={User}
          placeholder="Ahmed Khan"
          value={form.fullName}
          onChange={(e) => update("fullName", e.target.value)}
        />
        <TextField
          label={t("signup.mobileNumber")}
          autoComplete="tel"
          inputMode="numeric"
          icon={Phone}
          placeholder="0301 2345678"
          value={form.phone}
          onChange={(e) => update("phone", e.target.value)}
        />
        <TextField
          label={t("signup.email")}
          type="email"
          autoComplete="email"
          icon={Mail}
          placeholder="you@example.com"
          value={form.email}
          onChange={(e) => update("email", e.target.value)}
        />
        <TextField
          label={t("signup.password")}
          type="password"
          autoComplete="new-password"
          icon={Lock}
          placeholder="At least 8 characters"
          value={form.password}
          onChange={(e) => update("password", e.target.value)}
        />
        <TextField
          label={t("signup.confirmPassword")}
          type="password"
          autoComplete="new-password"
          icon={Lock}
          placeholder="••••••••"
          value={form.confirmPassword}
          onChange={(e) => update("confirmPassword", e.target.value)}
        />

        <label className="flex items-start gap-2.5 text-xs text-paper/60">
          <input
            type="checkbox"
            checked={agreed}
            onChange={(e) => setAgreed(e.target.checked)}
            className="mt-0.5 h-4 w-4 shrink-0 accent-gold"
          />
          {t("signup.agree")}{" "}
          <Link href="/terms" className="font-semibold text-gold-bright">
            {t("signup.termsOfService")}
          </Link>
        </label>

        {error && (
          <div className="flex items-start gap-2 rounded-xl bg-danger/10 px-3.5 py-3 text-sm text-danger">
            <AlertCircle size={16} className="mt-0.5 shrink-0" />
            {error}
          </div>
        )}

        <Button type="submit" size="lg" fullWidth disabled={loading}>
          {loading ? t("signup.creatingAccount") : t("signup.signUp")}
        </Button>
      </form>

      <p className="mt-6 text-center text-sm text-paper/60">
        {t("signup.alreadyHaveAccount")}{" "}
        <Link href="/login" className="font-semibold text-gold-bright">
          {t("signup.logIn")}
        </Link>
      </p>
    </AuthShell>
  );
}
