"use client";

import { useRouter, useSearchParams } from "next/navigation";
import { PageBand, SiteShell } from "@/components/SiteShell";
import { API } from "@/lib/api";
import { useEffect, useState, useRef } from "react";

type Plan = { id: number; plan_name: string; registration_fee: number; renewal_fee: number; duration_type: string; theme_color: string };
type FormStatus = "idle" | "loading" | "success" | "error";

export default function RegisterPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const preselectedPlan = searchParams.get("plan");

  const [plans, setPlans] = useState<Plan[]>([]);
  const [status, setStatus] = useState<FormStatus>("idle");
  const [errorMsg, setErrorMsg] = useState("");
  const [selectedPlanId, setSelectedPlanId] = useState(preselectedPlan || "");
  const [profileFile, setProfileFile] = useState<File | null>(null);
  const fileRef = useRef<HTMLInputElement>(null);
  const referralCode = searchParams.get("referral_code");

  useEffect(() => {
    fetch(`${API}/membership-plans`)
      .then((r) => r.json())
      .then(setPlans)
      .catch(() => undefined);
  }, []);

  useEffect(() => {
    if (preselectedPlan) setSelectedPlanId(preselectedPlan);
  }, [preselectedPlan]);

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setStatus("loading");
    setErrorMsg("");

    try {
      const form = e.currentTarget;
      const formData = new FormData(form);
      formData.set("membership_plan_id", selectedPlanId);

      const res = await fetch(`${API}/members/register`, {
        method: "POST",
        body: formData,
      });

      const data = await res.json();
      if (!res.ok) throw new Error(data.message || "Registration failed");

      setStatus("success");
      if (data.paymentUrl) {
        window.location.href = data.paymentUrl;
      } else {
        setTimeout(() => router.push(`/membership/status/${data.id}`), 1000);
      }
    } catch (err: any) {
      setStatus("error");
      setErrorMsg(err.message || "Something went wrong. Please try again.");
    }
  };

  return (
    <SiteShell>
      <section className="border-b border-[var(--color-hairline-cool)] bg-white">
        <div className="mx-auto max-w-[1280px] px-4 py-16 md:py-20 lg:px-6">
          <span className="eyebrow">
            <span className="eyebrow-dot" />
            Registration
          </span>
          <h1 className="mt-5 text-3xl leading-[1.1] tracking-[-0.02em] text-[var(--color-ink)] md:text-5xl" style={{ fontWeight: 500 }}>
            Become a Member
          </h1>
          <p className="mt-4 max-w-xl text-lg leading-7 text-[var(--color-ink-mute)]">
            Fill in your details to join the SKSF community. Fields marked with * are required.
          </p>
        </div>
      </section>

      <PageBand>
        <div className="mx-auto max-w-2xl">
          {status === "success" ? (
            <div className="rounded-[12px] border border-[var(--color-hairline)] bg-white p-10 text-center shadow-[var(--shadow-l1)]">
              <div className="mx-auto flex h-16 w-16 items-center justify-center rounded-full bg-[var(--color-primary)]/10">
                <svg width="32" height="32" fill="none" stroke="var(--color-primary-deep)" strokeWidth="2.5" viewBox="0 0 24 24">
                  <polyline points="20 6 9 17 4 12" />
                </svg>
              </div>
              <h2 className="mt-4 text-2xl text-[var(--color-ink)]" style={{ fontWeight: 500 }}>Registration Submitted!</h2>
              <p className="mt-2 text-sm text-[var(--color-ink-mute)]">Redirecting you to the next step...</p>
            </div>
          ) : (
            <form onSubmit={handleSubmit} className="grid gap-6">
              <div className="overflow-hidden rounded-[12px] border border-[var(--color-hairline)] bg-white shadow-[var(--shadow-l1)]">
                <div className="border-b border-[var(--color-hairline-cool)] p-7 sm:p-8">
                  <h2 className="text-xl text-[var(--color-ink)]" style={{ fontWeight: 500 }}>Personal Information</h2>
                  <p className="mt-1 text-sm text-[var(--color-ink-mute)]">Your basic details for the membership record.</p>
                </div>
                <div className="grid gap-4 p-7 sm:grid-cols-2 sm:p-8">
                  <input name="first_name" required placeholder="First Name *" className="input" />
                  <input name="last_name" placeholder="Last Name" className="input" />
                  <input name="phone" required type="tel" placeholder="Mobile Number *" className="input" />
                  <input name="alternate_mobile" type="tel" placeholder="Alternate Mobile" className="input" />
                  <input name="email" type="email" placeholder="Email Address" className="input sm:col-span-2" />
                  <textarea name="address" required placeholder="Address *" className="input min-h-20 sm:col-span-2" />
                  <input name="city" placeholder="City" className="input" />
                  <input name="state" placeholder="State" className="input" />
                  <input name="country" placeholder="Country" defaultValue="India" className="input" />
                  <input name="pincode" placeholder="Pincode" className="input" />
                </div>
              </div>

              <div className="overflow-hidden rounded-[12px] border border-[var(--color-hairline)] bg-white shadow-[var(--shadow-l1)]">
                <div className="border-b border-[var(--color-hairline-cool)] p-7 sm:p-8">
                  <h2 className="text-xl text-[var(--color-ink)]" style={{ fontWeight: 500 }}>Additional Details</h2>
                  <p className="mt-1 text-sm text-[var(--color-ink-mute)]">Optional but helps us serve you better.</p>
                </div>
                <div className="grid gap-4 p-7 sm:grid-cols-2 sm:p-8">
                  <input name="dob" type="date" placeholder="Date of Birth" className="input" />
                  <select name="gender" className="input">
                    <option value="">Gender</option>
                    <option>Male</option>
                    <option>Female</option>
                    <option>Other</option>
                  </select>
                  <input name="blood_group" placeholder="Blood Group" className="input" />
                  <input name="aadhaar_number" placeholder="Aadhaar Number" className="input" />
                  <input name="pan_number" placeholder="PAN Number" className="input" />
                  <input name="occupation" placeholder="Occupation" className="input" />
                  <input name="company_name" placeholder="Company / Organization" className="input sm:col-span-2" />
                  <input name="emergency_contact_name" placeholder="Emergency Contact Name" className="input" />
                  <input name="emergency_contact_number" type="tel" placeholder="Emergency Contact Number" className="input" />

                  <div className="sm:col-span-2">
                    <label className="flex cursor-pointer items-center gap-3 rounded-[6px] border-2 border-dashed border-[var(--color-hairline-strong)] bg-white p-4 text-sm font-medium text-[var(--color-ink-mute)] transition-all hover:border-[var(--color-ink)]">
                      <div className="flex h-10 w-10 items-center justify-center rounded-md bg-[var(--color-canvas-soft)] text-[var(--color-ink)]">
                        <svg width="20" height="20" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
                          <path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4" />
                          <polyline points="17 8 12 3 7 8" />
                          <line x1="12" y1="3" x2="12" y2="15" />
                        </svg>
                      </div>
                      <span className="flex-1 truncate">{profileFile ? profileFile.name : "Upload Profile Photo"}</span>
                      {profileFile && (
                        <button type="button" onClick={(e) => { e.stopPropagation(); setProfileFile(null); if (fileRef.current) fileRef.current.value = ""; }}
                          className="flex h-7 w-7 items-center justify-center rounded-full text-[var(--color-ink-mute)] hover:bg-[var(--color-canvas-soft)]">
                          <svg width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
                            <line x1="18" y1="6" x2="6" y2="18" /><line x1="6" y1="6" x2="18" y2="18" />
                          </svg>
                        </button>
                      )}
                      <input ref={fileRef} name="profile_img" type="file" accept="image/*" className="hidden" onChange={(e) => setProfileFile(e.target.files?.[0] || null)} />
                    </label>
                  </div>
                </div>
              </div>

              <div className="overflow-hidden rounded-[12px] border border-[var(--color-hairline)] bg-white shadow-[var(--shadow-l1)]">
                <div className="border-b border-[var(--color-hairline-cool)] p-7 sm:p-8">
                  <h2 className="text-xl text-[var(--color-ink)]" style={{ fontWeight: 500 }}>Membership Plan</h2>
                  <p className="mt-1 text-sm text-[var(--color-ink-mute)]">Choose your membership type.</p>
                </div>
                <div className="grid gap-3 p-7 sm:grid-cols-2 sm:p-8">
                  {plans.map((plan) => (
                    <label key={plan.id}
                      className={`flex cursor-pointer items-center gap-3 rounded-[6px] border p-4 transition-all ${String(plan.id) === selectedPlanId ? "border-[var(--color-ink)] bg-[var(--color-canvas-soft)] shadow-[var(--shadow-l1)]" : "border-[var(--color-hairline)] bg-white hover:border-[var(--color-hairline-strong)]"}`}>
                      <input type="radio" name="plan_radio" value={plan.id} checked={String(plan.id) === selectedPlanId}
                        onChange={() => setSelectedPlanId(String(plan.id))} className="sr-only" />
                      <div className={`flex h-5 w-5 items-center justify-center rounded-full border-2 ${String(plan.id) === selectedPlanId ? "border-[var(--color-ink)]" : "border-[var(--color-hairline-strong)]"}`}>
                        {String(plan.id) === selectedPlanId && <div className="h-2.5 w-2.5 rounded-full bg-[var(--color-ink)]" />}
                      </div>
                      <div className="flex-1">
                        <p className="text-sm font-medium text-[var(--color-ink)]">{plan.plan_name}</p>
                        <p className="text-xs text-[var(--color-ink-mute)]">₹{plan.registration_fee.toLocaleString()}</p>
                      </div>
                    </label>
                  ))}
                </div>
                <div className="p-7 sm:p-8 sm:pt-0">
                  <textarea name="notes" placeholder="Any additional notes or comments..." className="input min-h-20" />
                  {referralCode && <input name="referral_code" type="hidden" value={referralCode} />}
                </div>
              </div>

              {status === "error" && (
                <div className="flex items-center gap-2 rounded-[6px] border border-[var(--color-hairline)] bg-[var(--color-canvas-soft)] px-4 py-3 text-sm font-medium text-[var(--color-ink)]">
                  <svg width="16" height="16" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
                    <circle cx="12" cy="12" r="10" /><line x1="15" y1="9" x2="9" y2="15" /><line x1="9" y1="9" x2="15" y2="15" />
                  </svg>
                  {errorMsg}
                </div>
              )}

              <button
                className="btn w-full py-4 text-base"
                disabled={status === "loading" || !selectedPlanId}
              >
                {status === "loading" ? (
                  <><svg className="h-4 w-4 animate-spin" fill="none" viewBox="0 0 24 24"><circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" /><path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" /></svg> Submitting...</>
                ) : "Submit Registration"}
              </button>
            </form>
          )}
        </div>
      </PageBand>
    </SiteShell>
  );
}
