"use client";

import Link from "next/link";
import { useEffect, useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import { apiGet, apiPost } from "@/lib/api";

type SignupWorkspaceType = {
  value: string;
  label: string;
  description: string;
};

type SignupPlanOption = {
  id: string;
  name: string;
  status: "Draft" | "Live" | "Retired";
  planFamily: string;
  planVisibility: string;
  visibleWorkspaceTypes: string[];
  monthlyPrice: number;
  includedUsers: number;
  includedTrucks: number;
  includedPhoneNumbers: number;
  bestFor: string;
  featureAccess: Record<string, boolean>;
};

type SignupOptions = {
  workspaceTypes: SignupWorkspaceType[];
  plans: SignupPlanOption[];
  trialPolicy: {
    trialDays: number;
    startsWhenWorkspaceIsCreated: boolean;
    trialEndDateSaved: boolean;
    paymentRequiredAtSignup: boolean;
  };
  fallbackPolicy: {
    safeDefaultEnabled: boolean;
    fallbackLabel: string;
    workspaceTypesMissingStagedPlans: string[];
  };
  guardrails: {
    reviewOnly: boolean;
    stripeCheckoutActive: boolean;
    billingGateChanged: boolean;
    brokerDistributionChanged: boolean;
    ownedPortalRulesChanged: boolean;
    internalLoadBoardAccessChanged: boolean;
  };
};

type SignupCreateResult = {
  signupReview?: {
    selectedPlanName?: string | null;
    stagedPlanMatched?: boolean;
    fallbackUsed?: boolean;
    fallbackReason?: string | null;
    trialDays?: number;
    trialEndsAt?: string | null;
    reviewOnlySignup?: boolean;
    emailVerificationQueued?: boolean;
    emailVerificationDelivered?: boolean;
    emailVerificationStatus?: string | null;
  };
};

const fallbackWorkspaceTypes: SignupWorkspaceType[] = [
  {
    value: "DISPATCHER",
    label: "Dispatcher",
    description: "For dispatch companies managing carriers, trucks, loads, documents, and billing follow-up.",
  },
  {
    value: "COMPANY_FLEET",
    label: "Company / Fleet",
    description: "For fleets that own or manage multiple trucks, drivers, documents, routes, and finance workflows.",
  },
  {
    value: "CARRIER_OWNER_OPERATOR",
    label: "Carrier / Owner-Operator",
    description: "For small carriers or owner-operators that need a clean command center for loads and truck activity.",
  },
  {
    value: "FREIGHT_BROKER",
    label: "Freight Broker",
    description: "For broker teams that need customer, shipper, carrier, load, and document visibility without marketplace gates yet.",
  },
];

const defaultOptions: SignupOptions = {
  workspaceTypes: fallbackWorkspaceTypes,
  plans: [],
  trialPolicy: {
    trialDays: 14,
    startsWhenWorkspaceIsCreated: true,
    trialEndDateSaved: true,
    paymentRequiredAtSignup: false,
  },
  fallbackPolicy: {
    safeDefaultEnabled: true,
    fallbackLabel: "Safe default trial plan",
    workspaceTypesMissingStagedPlans: [],
  },
  guardrails: {
    reviewOnly: true,
    stripeCheckoutActive: false,
    billingGateChanged: false,
    brokerDistributionChanged: false,
    ownedPortalRulesChanged: false,
    internalLoadBoardAccessChanged: false,
  },
};

function money(value: number) {
  return `$${Math.round(value).toLocaleString()}`;
}

function featureSummary(plan: SignupPlanOption) {
  const included = [
    plan.featureAccess.cori ? "CORI" : null,
    plan.featureAccess.businessPhone ? "Business phone" : null,
    plan.featureAccess.routePlanning ? "Routes" : null,
    plan.featureAccess.reports ? "Reports" : null,
  ].filter(Boolean);
  return included.length ? included.join(" · ") : "Core workspace tools";
}

export default function SignUpPage() {
  const router = useRouter();
  const [form, setForm] = useState({
    companyName: "",
    companySlug: "",
    adminFirstName: "",
    adminLastName: "",
    adminEmail: "",
    adminPassword: "",
    workspaceType: "DISPATCHER",
    subscriptionPlanId: "",
  });
  const [options, setOptions] = useState<SignupOptions>(defaultOptions);
  const [loadingOptions, setLoadingOptions] = useState(true);
  const [optionsWarning, setOptionsWarning] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);
  const [working, setWorking] = useState(false);

  useEffect(() => {
    let cancelled = false;

    async function loadOptions() {
      try {
        const data = await apiGet<SignupOptions>("/api/auth/sign-up/options");
        if (cancelled) return;
        setOptions(data);
        setForm((current) => {
          const firstType = data.workspaceTypes[0]?.value ?? current.workspaceType;
          const workspaceType = data.workspaceTypes.some((type) => type.value === current.workspaceType) ? current.workspaceType : firstType;
          const matchingPlan = data.plans.find((plan) => plan.visibleWorkspaceTypes.includes(workspaceType));
          return { ...current, workspaceType, subscriptionPlanId: matchingPlan?.id ?? "" };
        });
        setOptionsWarning(null);
      } catch (err: any) {
        if (cancelled) return;
        setOptions(defaultOptions);
        setOptionsWarning(err?.message ?? "Plan choices are not available yet. Workspace creation can still continue.");
      } finally {
        if (!cancelled) setLoadingOptions(false);
      }
    }

    void loadOptions();

    return () => {
      cancelled = true;
    };
  }, []);

  const plansForType = useMemo(
    () => options.plans.filter((plan) => plan.visibleWorkspaceTypes.includes(form.workspaceType)),
    [form.workspaceType, options.plans]
  );

  const selectedWorkspaceType = options.workspaceTypes.find((type) => type.value === form.workspaceType) ?? options.workspaceTypes[0];
  const selectedPlan = plansForType.find((plan) => plan.id === form.subscriptionPlanId) ?? null;
  const trialDays = options.trialPolicy?.trialDays ?? 14;
  const usingSafeDefaultFallback = plansForType.length === 0;
  const fallbackReady = options.fallbackPolicy?.safeDefaultEnabled ?? true;
  const submitDisabled = working || (usingSafeDefaultFallback && !fallbackReady);

  function updateWorkspaceType(nextWorkspaceType: string) {
    const firstPlan = options.plans.find((plan) => plan.visibleWorkspaceTypes.includes(nextWorkspaceType));
    setForm((current) => ({ ...current, workspaceType: nextWorkspaceType, subscriptionPlanId: firstPlan?.id ?? "" }));
  }

  async function onSubmit(e: React.FormEvent) {
    e.preventDefault();
    try {
      setWorking(true);
      setError(null);
      setSuccess(null);
      const result = await apiPost<SignupCreateResult>('/api/auth/sign-up', form);
      const trialEndLabel = result.signupReview?.trialEndsAt ? new Date(result.signupReview.trialEndsAt).toLocaleDateString() : null;
      const verificationLabel = result.signupReview?.emailVerificationDelivered
        ? ' A verification email was sent to the admin email address.'
        : result.signupReview?.emailVerificationStatus === 'SKIPPED'
          ? ' Email delivery is not active, so the verification email was prepared but not sent.'
          : result.signupReview?.emailVerificationStatus === 'FAILED'
            ? ' The workspace was created, but the verification email needs to be resent after sign-in.'
            : '';
      setSuccess(trialEndLabel
        ? `Workspace created successfully. A ${result.signupReview?.trialDays ?? trialDays}-day trial was saved through ${trialEndLabel}.${verificationLabel} You can now sign in with the new admin account.`
        : `Workspace created successfully. Your selected workspace type and trial plan were saved for review.${verificationLabel} You can now sign in with the new admin account.`
      );
      setTimeout(() => router.push('/login'), 1000);
    } catch (err: any) {
      setError(err?.message ?? 'Failed to create workspace account');
    } finally {
      setWorking(false);
    }
  }

  return (
    <main className="min-h-screen bg-gray-50 px-4 py-8 md:px-6">
      <div className="mx-auto grid w-full max-w-6xl gap-6 lg:grid-cols-[minmax(0,1fr)_360px]">
        <div className="rounded-3xl border bg-white p-6 shadow-sm md:p-8">
          <div className="mb-6">
            <div className="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">Dispatch Spot signup</div>
            <h1 className="mt-1 text-2xl font-semibold text-slate-950">Create company workspace</h1>
            <p className="mt-2 max-w-2xl text-sm leading-6 text-gray-500">
              Choose the business type and staged trial plan first. This is a review-only signup step: no card is collected and no Stripe checkout is started.
            </p>
          </div>

          {optionsWarning ? <div className="mb-5 rounded-2xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-800">{optionsWarning}</div> : null}

          <form className="space-y-6" onSubmit={onSubmit}>
            <section className="rounded-2xl border border-slate-100 bg-slate-50 p-4">
              <div className="flex items-start justify-between gap-3">
                <div>
                  <h2 className="font-semibold text-slate-950">1. Select workspace type</h2>
                  <p className="mt-1 text-sm leading-6 text-slate-500">This saves the workspace classification so Super Admin and plan visibility reviews can use a real stored value.</p>
                </div>
                <span className="rounded-full bg-white px-2.5 py-1 text-xs font-semibold text-slate-600 ring-1 ring-slate-200">{selectedWorkspaceType?.label ?? "Workspace"}</span>
              </div>

              <div className="mt-4 grid gap-3 md:grid-cols-2">
                {options.workspaceTypes.map((type) => {
                  const active = form.workspaceType === type.value;
                  return (
                    <button
                      key={type.value}
                      type="button"
                      onClick={() => updateWorkspaceType(type.value)}
                      className={`rounded-2xl border p-4 text-left transition ${active ? "border-slate-950 bg-white shadow-sm" : "border-slate-200 bg-white hover:border-slate-300"}`}
                    >
                      <div className="font-semibold text-slate-950">{type.label}</div>
                      <div className="mt-1 text-sm leading-6 text-slate-500">{type.description}</div>
                    </button>
                  );
                })}
              </div>
            </section>

            <section className="rounded-2xl border border-slate-100 bg-slate-50 p-4">
              <div className="flex flex-col gap-2 md:flex-row md:items-start md:justify-between">
                <div>
                  <h2 className="font-semibold text-slate-950">2. Select staged trial plan</h2>
                  <p className="mt-1 text-sm leading-6 text-slate-500">Only Super Admin-staged Public or Invite only customer plans appear here. The choice creates a trial record for review, not checkout.</p>
                </div>
                {loadingOptions ? <span className="rounded-full bg-white px-2.5 py-1 text-xs font-semibold text-slate-500 ring-1 ring-slate-200">Loading plans...</span> : null}
              </div>

              <div className="mt-4 grid gap-3 md:grid-cols-2">
                {plansForType.length ? plansForType.map((plan) => {
                  const active = form.subscriptionPlanId === plan.id;
                  return (
                    <button
                      key={plan.id}
                      type="button"
                      onClick={() => setForm((current) => ({ ...current, subscriptionPlanId: plan.id }))}
                      className={`rounded-2xl border bg-white p-4 text-left transition ${active ? "border-slate-950 shadow-sm" : "border-slate-200 hover:border-slate-300"}`}
                    >
                      <div className="flex items-start justify-between gap-3">
                        <div>
                          <div className="font-semibold text-slate-950">{plan.name}</div>
                          <div className="mt-1 text-xs font-semibold uppercase tracking-[0.14em] text-slate-400">{plan.status} · {plan.planVisibility}</div>
                        </div>
                        <div className="text-right">
                          <div className="text-lg font-semibold text-slate-950">{money(plan.monthlyPrice)}</div>
                          <div className="text-xs text-slate-500">per month after trial</div>
                        </div>
                      </div>
                      <div className="mt-3 text-sm leading-6 text-slate-600">{plan.bestFor || "Staged Dispatch Spot workspace plan."}</div>
                      <div className="mt-3 grid gap-2 text-xs text-slate-600 sm:grid-cols-3">
                        <span className="rounded-lg bg-slate-50 px-2 py-1">{plan.includedUsers} users</span>
                        <span className="rounded-lg bg-slate-50 px-2 py-1">{plan.includedTrucks} trucks</span>
                        <span className="rounded-lg bg-slate-50 px-2 py-1">{plan.includedPhoneNumbers} phone #</span>
                      </div>
                      <div className="mt-3 text-xs font-medium text-slate-500">{featureSummary(plan)}</div>
                    </button>
                  );
                }) : (
                  <div className={`rounded-2xl border p-4 text-sm leading-6 md:col-span-2 ${fallbackReady ? "border-amber-100 bg-white text-amber-800" : "border-red-100 bg-red-50 text-red-700"}`}>
                    {fallbackReady
                      ? <>No plan choices are staged for {selectedWorkspaceType?.label ?? "this workspace type"} yet. Signup will still create a {trialDays}-day trial workspace using the safe default plan, and Super Admin can clean up the assigned plan later.</>
                      : <>No safe default trial plan is ready. Super Admin needs to stage or repair a fallback plan before this signup can continue.</>}
                  </div>
                )}
              </div>
            </section>

            <section className="rounded-2xl border border-slate-100 bg-slate-50 p-4">
              <h2 className="font-semibold text-slate-950">3. Add workspace and admin details</h2>
              <p className="mt-1 text-sm leading-6 text-slate-500">This creates the workspace and the first Workspace Admin user.</p>
              <div className="mt-4 grid gap-4 md:grid-cols-2">
                <input className="w-full rounded-xl border bg-white px-3 py-2" value={form.companyName} onChange={(e) => setForm((p) => ({ ...p, companyName: e.target.value }))} placeholder="Company name" />
                <input className="w-full rounded-xl border bg-white px-3 py-2" value={form.companySlug} onChange={(e) => setForm((p) => ({ ...p, companySlug: e.target.value }))} placeholder="Workspace slug (optional)" />
              </div>
              <div className="mt-4 grid gap-4 md:grid-cols-2">
                <input className="w-full rounded-xl border bg-white px-3 py-2" value={form.adminFirstName} onChange={(e) => setForm((p) => ({ ...p, adminFirstName: e.target.value }))} placeholder="Admin first name" />
                <input className="w-full rounded-xl border bg-white px-3 py-2" value={form.adminLastName} onChange={(e) => setForm((p) => ({ ...p, adminLastName: e.target.value }))} placeholder="Admin last name" />
              </div>
              <div className="mt-4 grid gap-4 md:grid-cols-[1fr_260px]">
                <input type="email" className="w-full rounded-xl border bg-white px-3 py-2" value={form.adminEmail} onChange={(e) => setForm((p) => ({ ...p, adminEmail: e.target.value }))} placeholder="Admin email" />
                <input type="password" className="w-full rounded-xl border bg-white px-3 py-2" value={form.adminPassword} onChange={(e) => setForm((p) => ({ ...p, adminPassword: e.target.value }))} placeholder="Temporary password" />
              </div>
            </section>

            {error ? <div className="rounded-xl border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700">{error}</div> : null}
            {success ? <div className="rounded-xl border border-green-200 bg-green-50 px-3 py-2 text-sm text-green-700">{success}</div> : null}
            <button type="submit" disabled={submitDisabled} className="w-full rounded-xl bg-black px-4 py-2.5 text-sm font-medium text-white disabled:opacity-60">{working ? 'Creating workspace...' : usingSafeDefaultFallback && !fallbackReady ? 'Signup needs plan review' : 'Create review-only trial workspace'}</button>
          </form>
          <div className="mt-6 text-sm text-gray-500">Already have a workspace? <Link className="font-medium text-gray-900 underline" href="/login">Sign in</Link></div>
        </div>

        <aside className="rounded-3xl border bg-white p-6 shadow-sm lg:sticky lg:top-6 lg:self-start">
          <div className="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">Signup review summary</div>
          <h2 className="mt-1 text-lg font-semibold text-slate-950">What will be saved</h2>
          <div className="mt-4 space-y-3 text-sm">
            <div className="rounded-2xl border border-slate-100 bg-slate-50 p-3">
              <div className="text-xs font-semibold uppercase tracking-[0.14em] text-slate-400">Workspace type</div>
              <div className="mt-1 font-semibold text-slate-950">{selectedWorkspaceType?.label ?? "Dispatcher"}</div>
              <p className="mt-1 leading-6 text-slate-500">Saved as a paid workspace classification for Super Admin review.</p>
            </div>
            <div className="rounded-2xl border border-slate-100 bg-slate-50 p-3">
              <div className="text-xs font-semibold uppercase tracking-[0.14em] text-slate-400">Trial plan</div>
              <div className="mt-1 font-semibold text-slate-950">{selectedPlan?.name ?? "Safe default plan"}</div>
              <p className="mt-1 leading-6 text-slate-500">Saved as a trial subscription. No checkout session or live billing is created.</p>
              {usingSafeDefaultFallback ? <p className="mt-2 rounded-xl bg-amber-50 px-3 py-2 text-xs leading-5 text-amber-800">This workspace type is using the safe default fallback because no staged plan is visible yet.</p> : null}
            </div>
            <div className="rounded-2xl border border-slate-100 bg-slate-50 p-3">
              <div className="text-xs font-semibold uppercase tracking-[0.14em] text-slate-400">Trial dates</div>
              <div className="mt-1 font-semibold text-slate-950">{trialDays}-day trial</div>
              <p className="mt-1 leading-6 text-slate-500">The trial starts when the workspace is created and a trial end date is saved for Super Admin review.</p>
            </div>
          </div>
          <div className="mt-5 rounded-2xl border border-blue-100 bg-blue-50 p-4 text-sm leading-6 text-blue-900">
            <div className="font-semibold text-blue-950">Guardrails still active</div>
            <p className="mt-1">This step does not collect payment, start Stripe checkout, enforce hard billing gates, open broker distribution, change portal ownership, or open internal load-board access.</p>
          </div>
        </aside>
      </div>
    </main>
  );
}
