"use client";

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

interface FormState {
  organizationName: string;
  fullName: string;
  email: string;
  phone: string;
  password: string;
}

const initialState: FormState = { organizationName: "", fullName: "", email: "", phone: "", password: "" };

export default function RegisterPage() {
  const router = useRouter();
  const [form, setForm] = useState<FormState>(initialState);
  const [error, setError] = useState<string | null>(null);
  const [fieldErrors, setFieldErrors] = useState<Record<string, string[]>>({});
  const [submitting, setSubmitting] = useState(false);

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

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    setFieldErrors({});
    setSubmitting(true);
    try {
      await apiFetch("/api/v1/auth/register", {
        method: "POST",
        body: JSON.stringify({ ...form, phone: form.phone || undefined }),
      });
      router.push("/dashboard");
      router.refresh();
    } catch (err) {
      if (err instanceof ApiClientError) {
        setError(err.message);
        const fieldErrorMap = (err.details as any)?.fieldErrors;
        if (fieldErrorMap) setFieldErrors(fieldErrorMap);
      } else {
        setError("Something went wrong. Please try again.");
      }
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <div className="flex min-h-screen items-center justify-center bg-canvas px-4 py-10">
      <div className="w-full max-w-sm">
        <h1 className="mb-1 text-lg font-semibold text-ink">Create your organization</h1>
        <p className="mb-6 text-sm text-ink-muted">You'll be the Owner and can invite staff afterward.</p>

        <form onSubmit={handleSubmit} className="flex flex-col gap-4">
          <Input
            label="Organization name"
            name="organizationName"
            placeholder="e.g. Coastline WiFi"
            required
            value={form.organizationName}
            onChange={(e) => update("organizationName", e.target.value)}
            error={fieldErrors.organizationName?.[0]}
          />
          <Input
            label="Your full name"
            name="fullName"
            required
            value={form.fullName}
            onChange={(e) => update("fullName", e.target.value)}
            error={fieldErrors.fullName?.[0]}
          />
          <Input
            label="Email"
            type="email"
            name="email"
            autoComplete="email"
            required
            value={form.email}
            onChange={(e) => update("email", e.target.value)}
            error={fieldErrors.email?.[0]}
          />
          <Input
            label="Phone (optional)"
            type="tel"
            name="phone"
            value={form.phone}
            onChange={(e) => update("phone", e.target.value)}
            error={fieldErrors.phone?.[0]}
          />
          <Input
            label="Password"
            type="password"
            name="password"
            autoComplete="new-password"
            required
            hint="At least 10 characters, with upper and lower case letters and a number."
            value={form.password}
            onChange={(e) => update("password", e.target.value)}
            error={fieldErrors.password?.[0]}
          />

          {error && <p className="text-sm text-status-offline">{error}</p>}

          <Button type="submit" disabled={submitting} className="mt-1 w-full">
            {submitting ? "Creating…" : "Create organization"}
          </Button>
        </form>

        <p className="mt-6 text-center text-sm text-ink-muted">
          Already have an account?{" "}
          <Link href="/login" className="font-medium text-primary">
            Log in
          </Link>
        </p>
      </div>
    </div>
  );
}
