"use client";
import { useParams, useRouter } from "next/navigation";
import { useState } from "react";
import Link from "next/link";
import CommonError from "@/app/components/CommonError";
import { registerCustomer } from "../../_lib/storeApiCalls";
import { setCustomerToken } from "../../_lib/storeApi";

export default function RegisterPage() {
  const params = useParams<{ orgSlug: string }>();
  const router = useRouter();
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [phone, setPhone] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");
  const [submitting, setSubmitting] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(""); setSubmitting(true);
    try {
      const { token } = await registerCustomer(params.orgSlug, { name, email, password, phone });
      setCustomerToken(params.orgSlug, token);
      router.push(`/${params.orgSlug}`);
    } catch (err: any) {
      setError(err?.response?.data?.error || "Could not create account.");
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="mx-auto" style={{ maxWidth: 420 }}>
      <h3 className="mb-4 text-center">Create Account</h3>
      <CommonError message={error} type="error" />
      <form onSubmit={handleSubmit} className="card card-body">
        <label className="form-label">Full Name</label>
        <input className="form-control mb-3" value={name} onChange={(e) => setName(e.target.value)} required />
        <label className="form-label">Email</label>
        <input className="form-control mb-3" type="email" value={email} onChange={(e) => setEmail(e.target.value)} required />
        <label className="form-label">Phone</label>
        <input className="form-control mb-3" value={phone} onChange={(e) => setPhone(e.target.value)} />
        <label className="form-label">Password</label>
        <input className="form-control mb-3" type="password" value={password} onChange={(e) => setPassword(e.target.value)} required minLength={8} />
        <button className="btn btn-primary" disabled={submitting}>{submitting ? "Creating..." : "Create Account"}</button>
        <p className="text-center small mt-3 mb-0">
          Already have an account? <Link href={`/${params.orgSlug}/account/login`}>Sign in</Link>
        </p>
      </form>
    </div>
  );
}
