/**
 * Review Step - Summary and terms acceptance
 */

"use client";

import Link from "next/link";

type FormErrors = Record<string, string | undefined>;

/** Format field names for display (e.g., "address.city" → "City") */
function formatFieldName(field: string): string {
  return field
    .replace("address.", "")
    .replace(/([A-Z])/g, " $1")
    .replace(/^./, s => s.toUpperCase())
    .trim();
}

/** Display validation errors from previous steps */
function ValidationErrors({ errors }: { errors: FormErrors }) {
  // Collect errors excluding acceptTerms (shown inline) and _form (shown separately)
  const fieldErrors = Object.entries(errors)
    .filter(([key, value]) => value && key !== "acceptTerms" && key !== "_form")
    .map(([key, value]) => ({ field: key, message: value }));

  const hasErrors = fieldErrors.length > 0 || errors["_form"];
  if (!hasErrors) return null;

  return (
    <div className="bg-red-50 border border-red-200 rounded-xl p-4 text-sm text-red-800">
      <p className="font-medium mb-2">Please fix the following errors:</p>
      <ul className="list-disc list-inside space-y-1">
        {errors["_form"] && <li>{errors["_form"]}</li>}
        {fieldErrors.map(({ field, message }) => (
          <li key={field}>
            <span className="font-medium">{formatFieldName(field)}:</span> {message}
          </li>
        ))}
      </ul>
    </div>
  );
}

/** Ready message shown when form is valid */
function ReadyMessage({ errors }: { errors: FormErrors }) {
  const hasErrors = Object.values(errors).some(Boolean);
  if (hasErrors) return null;

  return (
    <div className="bg-info-soft border border-info/25 rounded-xl p-4 text-sm text-info flex items-start gap-3">
      <span className="text-lg">🚀</span>
      <div>
        <p className="font-medium">Ready to create your account!</p>
        <p className="text-foreground/80 mt-1">
          Click &quot;Create Account&quot; below to complete your registration.
        </p>
      </div>
    </div>
  );
}

interface ReviewStepProps {
  form: {
    values: {
      firstName: string;
      lastName: string;
      email: string;
      phone: string;
      phoneCountryCode: string;
      company?: string;
      dateOfBirth?: string;
      gender?: "male" | "female" | "other";
      address: {
        address1: string;
        address2: string;
        city: string;
        state: string;
        postcode: string;
        country: string;
      };
      acceptTerms: boolean;
      marketingConsent?: boolean;
    };
    errors: Record<string, string | undefined>;
    touched: Record<string, boolean | undefined>;
    setValue: (field: string, value: unknown) => void;
    setTouchedField: (field: string) => void;
  };
}

export function ReviewStep({ form }: ReviewStepProps) {
  const { values, errors, setValue, setTouchedField } = form;
  const address = values.address;

  // Format address for display
  const formattedAddress = [
    address.address2,
    address.address1,
    address.city,
    address.state,
    address.postcode,
  ]
    .filter(Boolean)
    .join(", ");

  return (
    <div className="space-y-6">
      {/* Account Summary */}
      <div className="bg-muted rounded-xl p-5 border border-border">
        <h4 className="text-sm font-semibold text-foreground mb-4 flex items-center gap-2">
          <span className="w-6 h-6 bg-primary/10 rounded-full flex items-center justify-center text-xs text-primary">
            ✓
          </span>
          Account Summary
        </h4>
        <dl className="space-y-3 text-sm">
          <div className="flex justify-between py-2 border-b border-border/60">
            <dt className="text-muted-foreground">Name</dt>
            <dd className="text-foreground font-medium">
              {values.firstName} {values.lastName}
            </dd>
          </div>
          <div className="flex justify-between py-2 border-b border-border/60">
            <dt className="text-muted-foreground">Email</dt>
            <dd className="text-foreground font-medium break-all">{values.email}</dd>
          </div>
          <div className="flex justify-between py-2 border-b border-border/60">
            <dt className="text-muted-foreground">Phone</dt>
            <dd className="text-foreground font-medium">
              {values.phoneCountryCode} {values.phone}
            </dd>
          </div>
          {values.company && (
            <div className="flex justify-between py-2 border-b border-border/60">
              <dt className="text-muted-foreground">Company</dt>
              <dd className="text-foreground font-medium">{values.company}</dd>
            </div>
          )}
          {values.dateOfBirth && (
            <div className="flex justify-between py-2 border-b border-border/60">
              <dt className="text-muted-foreground">Date of Birth</dt>
              <dd className="text-foreground font-medium">{values.dateOfBirth}</dd>
            </div>
          )}
          {values.gender && (
            <div className="flex justify-between py-2 border-b border-border/60">
              <dt className="text-muted-foreground">Gender</dt>
              <dd className="text-foreground font-medium">{values.gender}</dd>
            </div>
          )}
        </dl>
      </div>

      {/* Address Summary */}
      {address?.address1 && (
        <div className="bg-muted rounded-xl p-5 border border-border">
          <h4 className="text-sm font-semibold text-foreground mb-4 flex items-center gap-2">
            <span className="w-6 h-6 bg-success-soft rounded-full flex items-center justify-center text-xs text-success">
              📍
            </span>
            Delivery Address
          </h4>
          <p className="text-sm text-foreground/80 font-medium">{formattedAddress}</p>
        </div>
      )}

      {/* Terms & Conditions */}
      <div className="space-y-4 bg-card rounded-xl p-5 border border-border">
        <h4 className="text-sm font-semibold text-foreground">Terms & Agreements</h4>

        <label className="flex items-start gap-3 cursor-pointer p-3 rounded-lg hover:bg-muted transition-colors">
          <input
            type="checkbox"
            checked={values.acceptTerms}
            onChange={e => setValue("acceptTerms", e.target.checked)}
            onBlur={() => setTouchedField("acceptTerms")}
            className="mt-0.5 h-5 w-5 text-primary border-input rounded focus:ring-ring"
          />
          <span className="text-sm text-foreground/80">
            I accept the{" "}
            <Link
              href="/terms"
              className="text-primary hover:underline font-medium"
              target="_blank"
            >
              Terms of Service
            </Link>{" "}
            and{" "}
            <Link
              href="/privacy"
              className="text-primary hover:underline font-medium"
              target="_blank"
            >
              Privacy Policy
            </Link>
            <span className="text-red-500 ml-1">*</span>
          </span>
        </label>
        {errors["acceptTerms"] && (
          <p className="text-sm text-danger ml-11 -mt-2">{errors["acceptTerms"]}</p>
        )}

        <label className="flex items-start gap-3 cursor-pointer p-3 rounded-lg hover:bg-muted transition-colors">
          <input
            type="checkbox"
            checked={values.marketingConsent ?? false}
            onChange={e => setValue("marketingConsent", e.target.checked)}
            className="mt-0.5 h-5 w-5 text-primary border-input rounded focus:ring-ring"
          />
          <span className="text-sm text-foreground/80">
            Send me updates about new products and promotions
            <span className="block text-xs text-muted-foreground mt-0.5">
              You can unsubscribe anytime
            </span>
          </span>
        </label>
      </div>

      <ValidationErrors errors={errors} />

      <ReadyMessage errors={errors} />
    </div>
  );
}
