import React, { useState } from "react";
import {
  CalendarIcon,
  CheckIcon,
  CreditCardIcon,
  MailIcon,
  PhoneIcon,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { Button } from "./button";
import { Checkbox } from "./checkbox";
import { Field, FieldError, FieldLabel } from "./field";
import { Input } from "./input";
import { Separator } from "./separator";
import { PasswordField, SectionHeading } from "./signup-form-primitives";

// ---------------------------------------------------------------------------
// Plan model (wealthx.au/pricing)
// ---------------------------------------------------------------------------
//
// The plan selector shows 4 plans, but onboarding has only 2 profiles:
//   broker_starter / broker_growth -> "broker"  (team, aggregator, AI, extension)
//   accountant     / planner       -> "planner" (no team, channels only)
// Enterprise is not self-serve — a system admin adds the company manually.

export type PlanId =
  | "broker_starter"
  | "broker_growth"
  | "accountant"
  | "planner";

export type PlanProfile = "broker" | "planner";

export interface PlanConfig {
  id: PlanId;
  name: string;
  description: string;
  price: number;
  profile: PlanProfile;
  features: string[];
}

export const PLAN_CONFIG: PlanConfig[] = [
  {
    id: "broker_starter",
    name: "Broker Starter",
    description: "Everything a solo broker needs to get started.",
    price: 75,
    profile: "broker",
    features: [
      "50 active connections (+$1 per additional)",
      "Website templates",
      "Digital fact find",
      "CRM Kanban",
      "Client wealth app",
      "Email support",
    ],
  },
  {
    id: "broker_growth",
    name: "Broker Growth",
    description: "AI and automation for scaling brokerages.",
    price: 99,
    profile: "broker",
    features: [
      "Everything in Starter",
      "WealthX AI",
      "Aggregator sync (Connective, AFG…)",
      "Chrome / Edge co-pilot",
      "Priority support",
    ],
  },
  {
    id: "accountant",
    name: "Accountant",
    description: "Client portal and document management.",
    price: 79,
    profile: "planner",
    features: [
      "Unlimited client connections",
      "Document vault",
      "Tax & accounting workflow",
      "Client wealth app",
      "Email support",
    ],
  },
  {
    id: "planner",
    name: "Planner",
    description: "SOA tools and financial planning workflow.",
    price: 79,
    profile: "planner",
    features: [
      "Unlimited client connections",
      "SOA generation",
      "Financial planning workflow",
      "Client wealth app",
      "Email support",
    ],
  },
];

/** Resolve the onboarding profile (broker vs planner) for a chosen plan. */
export function getPlanProfile(id: PlanId): PlanProfile {
  return PLAN_CONFIG.find((p) => p.id === id)?.profile ?? "broker";
}

// ---------------------------------------------------------------------------
// Shared primitives (internal)
// ---------------------------------------------------------------------------

function PlanCard({
  plan,
  isSelected,
  priceUnit,
  onClick,
}: {
  plan: PlanConfig;
  isSelected: boolean;
  priceUnit: string;
  onClick: () => void;
}) {
  return (
    <button
      type="button"
      onClick={onClick}
      aria-pressed={isSelected}
      className={cn(
        "flex flex-col gap-4 p-4 text-left transition-colors border-2",
        isSelected
          ? "border-primary bg-primary/5"
          : "border-border hover:border-muted-foreground",
      )}
    >
      <div className="flex items-start justify-between gap-3">
        <div className="flex flex-col gap-0.5">
          <p className="text-label-medium">{plan.name}</p>
          <p className="text-caption text-muted-foreground">
            {plan.description}
          </p>
        </div>
        <p className="text-h4 shrink-0">
          ${plan.price}
          <span className="text-caption text-muted-foreground">
            {priceUnit}
          </span>
        </p>
      </div>
      <Separator />
      <ul className="flex flex-col gap-1.5">
        {plan.features.map((f) => (
          <li
            key={f}
            className="flex items-start gap-2 text-caption text-muted-foreground"
          >
            <CheckIcon className="size-3 mt-0.5 text-foreground shrink-0" />
            {f}
          </li>
        ))}
      </ul>
    </button>
  );
}

function CardDetailsBlock() {
  return (
    <div className="border border-border p-6 flex flex-col gap-4">
      <Field>
        <FieldLabel>Card Number</FieldLabel>
        <div className="flex h-9 w-full border border-input bg-muted/30 px-3 py-2 text-body-small text-muted-foreground items-center">
          •••• •••• •••• 4242
        </div>
      </Field>
      <div className="flex gap-4">
        <Field className="flex-1">
          <FieldLabel>Expiry</FieldLabel>
          <div className="flex h-9 w-full border border-input bg-muted/30 px-3 py-2 text-body-small text-muted-foreground items-center">
            MM / YY
          </div>
        </Field>
        <Field className="flex-1">
          <FieldLabel>CVC</FieldLabel>
          <div className="flex h-9 w-full border border-input bg-muted/30 px-3 py-2 text-body-small text-muted-foreground items-center">
            •••
          </div>
        </Field>
      </div>
      <p className="text-caption text-muted-foreground">
        Powered by Stripe. Your payment information is encrypted and secure.
      </p>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Step 1 — Create Account
// ---------------------------------------------------------------------------

export interface PersonalDetailsStepProps {
  onValidChange?: (valid: boolean) => void;
  /** When provided the email field is pre-filled and disabled. */
  lockedEmail?: string;
}

export function PersonalDetailsStep({
  onValidChange,
  lockedEmail,
}: PersonalDetailsStepProps) {
  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
  const [email, setEmail] = useState("");
  const [emailError, setEmailError] = useState("");
  const [emailTouched, setEmailTouched] = useState(false);
  const [passwordValue, setPasswordValue] = useState("");
  const [confirmValue, setConfirmValue] = useState("");
  const [termsAccepted, setTermsAccepted] = useState(false);

  const validateEmail = (v: string) => {
    if (v.length > 0 && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v))
      return "Please enter a valid email address";
    return "";
  };

  const passwordRules = (v: string) =>
    v.length >= 8 &&
    /[A-Z]/.test(v) &&
    /[a-z]/.test(v) &&
    /[0-9]/.test(v) &&
    /[^A-Za-z0-9]/.test(v);

  const emailValid =
    lockedEmail !== undefined ||
    (email.length > 0 && validateEmail(email) === "");
  const passwordValid = passwordRules(passwordValue);
  const confirmPasswordValid =
    confirmValue.length > 0 && confirmValue === passwordValue;

  React.useEffect(() => {
    onValidChange?.(
      firstName.trim().length > 0 &&
        lastName.trim().length > 0 &&
        emailValid &&
        passwordValid &&
        confirmPasswordValid &&
        termsAccepted,
    );
  }, [
    firstName,
    lastName,
    emailValid,
    passwordValid,
    confirmPasswordValid,
    termsAccepted,
    onValidChange,
  ]);

  return (
    <div className="flex flex-col gap-1">
      <div className="flex gap-4">
        <Field>
          <FieldLabel>
            First Name<span className="text-destructive ml-0.5">*</span>
          </FieldLabel>
          <Input
            placeholder="First Name"
            value={firstName}
            onChange={(e) => setFirstName(e.target.value)}
          />
          <div className="min-h-5" />
        </Field>
        <Field>
          <FieldLabel>
            Last Name<span className="text-destructive ml-0.5">*</span>
          </FieldLabel>
          <Input
            placeholder="Last Name"
            value={lastName}
            onChange={(e) => setLastName(e.target.value)}
          />
          <div className="min-h-5" />
        </Field>
      </div>
      <Field>
        <FieldLabel>
          Email Address<span className="text-destructive ml-0.5">*</span>
        </FieldLabel>
        {lockedEmail !== undefined ? (
          <Input
            type="email"
            value={lockedEmail}
            disabled
            className="bg-muted text-muted-foreground cursor-not-allowed"
          />
        ) : (
          <Input
            type="email"
            placeholder="Email Address"
            value={email}
            onChange={(e) => {
              setEmail(e.target.value);
              if (emailTouched) setEmailError(validateEmail(e.target.value));
            }}
            onBlur={() => {
              setEmailTouched(true);
              setEmailError(validateEmail(email));
            }}
          />
        )}
        <div className="min-h-5">
          {emailTouched && emailError && <FieldError>{emailError}</FieldError>}
        </div>
      </Field>
      <PasswordField
        label="Set Your Password"
        placeholder="Password"
        required
        showStrengthPopover
        onValueChange={setPasswordValue}
      />
      <PasswordField
        label="Confirm Password"
        placeholder="Confirm Your Password"
        required
        onValueChange={setConfirmValue}
      />
      <Field>
        <FieldLabel>Phone Number</FieldLabel>
        <Input placeholder="Phone Number" />
        <div className="min-h-5" />
      </Field>
      <div className="flex items-start gap-3">
        <Checkbox
          id="terms"
          checked={termsAccepted}
          onCheckedChange={(v) => setTermsAccepted(!!v)}
        />
        <label
          htmlFor="terms"
          className="text-body-small text-muted-foreground cursor-pointer select-none"
        >
          I agree to the{" "}
          <span className="text-foreground underline">
            Terms and Conditions
          </span>{" "}
          and <span className="text-foreground underline">Privacy Policy</span>
        </label>
      </div>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Step 2 — Plan & Payment
// ---------------------------------------------------------------------------

export interface PlanPaymentStepProps {
  /** Selected plan — preselected from the landing page, re-selectable here. */
  value: PlanId;
  onChange: (id: PlanId) => void;
}

export function PlanPaymentStep({ value, onChange }: PlanPaymentStepProps) {
  return (
    <div className="flex flex-col gap-6">
      <div className="flex flex-col gap-3">
        <SectionHeading>Select Plan</SectionHeading>
        <div className="grid grid-cols-2 gap-3">
          {PLAN_CONFIG.map((plan) => (
            <PlanCard
              key={plan.id}
              plan={plan}
              isSelected={value === plan.id}
              priceUnit="/month"
              onClick={() => onChange(plan.id)}
            />
          ))}
        </div>
        <p className="text-caption text-muted-foreground text-center">
          No lock-in contract · Cancel anytime · 30-day free trial
        </p>
      </div>

      <div className="flex flex-col gap-3">
        <SectionHeading>Payment Details</SectionHeading>
        <CardDetailsBlock />
      </div>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Step 3 — Confirmation
// ---------------------------------------------------------------------------

function SummaryRow({ label, value }: { label: string; value: string }) {
  return (
    <div className="flex items-center justify-between gap-4 text-body-small">
      <span className="text-muted-foreground">{label}</span>
      <span className="text-label-medium text-foreground text-right">
        {value}
      </span>
    </div>
  );
}

export interface SignupConfirmationStepProps {
  name: string;
  email: string;
  planId: PlanId;
  /** Masked card brand + last 4 digits — shown read-only. */
  cardBrand?: string;
  cardLast4?: string;
  /** Jump back to an earlier step to edit. */
  onEditAccount?: () => void;
  onEditPlan?: () => void;
}

export function SignupConfirmationStep({
  name,
  email,
  planId,
  cardBrand = "Visa",
  cardLast4 = "4242",
  onEditAccount,
  onEditPlan,
}: SignupConfirmationStepProps) {
  const plan = PLAN_CONFIG.find((p) => p.id === planId)!;

  return (
    <div className="flex flex-col gap-6">
      <p className="text-body-small text-muted-foreground">
        Review your details before we create your account. To make changes, go
        back to the relevant step.
      </p>

      <section className="flex flex-col gap-3 border border-border p-5">
        <div className="flex items-center justify-between">
          <SectionHeading>Account</SectionHeading>
          {onEditAccount && (
            <Button
              variant="link"
              size="sm"
              className="h-auto p-0"
              onClick={onEditAccount}
            >
              Edit
            </Button>
          )}
        </div>
        <SummaryRow label="Name" value={name} />
        <SummaryRow label="Email" value={email} />
      </section>

      <section className="flex flex-col gap-3 border border-border p-5">
        <div className="flex items-center justify-between">
          <SectionHeading>Plan & Payment</SectionHeading>
          {onEditPlan && (
            <Button
              variant="link"
              size="sm"
              className="h-auto p-0"
              onClick={onEditPlan}
            >
              Edit
            </Button>
          )}
        </div>
        <SummaryRow label="Plan" value={plan.name} />
        <SummaryRow label="Price" value={`$${plan.price}/month`} />
        <Separator />
        <div className="flex items-center gap-2.5">
          <CreditCardIcon className="size-5 text-muted-foreground shrink-0" />
          <span className="text-body-small text-foreground">
            {cardBrand} •••• {cardLast4}
          </span>
        </div>
      </section>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Success screen
// ---------------------------------------------------------------------------

export function BackofficeSuccessStep() {
  return (
    <div className="flex flex-col items-center justify-center min-h-full py-16 gap-6 text-center px-4">
      <div className="size-16 bg-success/10 flex items-center justify-center">
        <svg
          viewBox="0 0 24 24"
          className="size-8 text-success"
          fill="none"
          stroke="currentColor"
          strokeWidth={2}
        >
          <polyline points="20 6 9 17 4 12" />
        </svg>
      </div>
      <div className="flex flex-col gap-2">
        <h2 className="text-h3 text-foreground">You're all set!</h2>
        <p className="text-muted-foreground max-w-[400px]">
          We've emailed you the next steps to set up your workspace. Let's get
          you onboarded.
        </p>
      </div>
      <div className="border border-border p-6 flex flex-col gap-4 text-left w-full max-w-[400px]">
        <p className="text-label-large text-foreground">
          Contact us anytime if you have any concerns.
        </p>
        <div className="flex items-center gap-2.5">
          <PhoneIcon className="size-5 text-success shrink-0" />
          <span className="text-body-medium text-foreground">0416 338 438</span>
        </div>
        <div className="flex items-center gap-2.5">
          <CalendarIcon className="size-5 text-success shrink-0" />
          <span className="text-body-medium text-foreground">
            Book call back
          </span>
        </div>
        <div className="flex items-center gap-2.5">
          <MailIcon className="size-5 text-success shrink-0" />
          <span className="text-body-medium text-foreground">
            clint@wealthx.au
          </span>
        </div>
      </div>
    </div>
  );
}
