/**
 * MigrateAccountStep - Migrate WHMCS account to portal (passwordless)
 *
 * For whmcs_unmapped users who have verified their email via OTP.
 * Email verification serves as identity proof - no legacy password needed.
 * Shows prefilled WHMCS data and collects password + terms.
 * DOB and gender are not collected here — WHMCS already has them.
 */

"use client";

import { useState } from "react";
import { Button, Input, PasswordInput, Label } from "@/components/atoms";
import { Checkbox } from "@/components/atoms/checkbox";
import { PasswordRequirements, PasswordMatchIndicator } from "@/features/auth/components";
import { usePasswordValidation } from "@/features/auth/hooks/usePasswordValidation";
import { useGetStartedMachine } from "../../../hooks/useGetStartedMachine";

interface FormErrors {
  password?: string | undefined;
  confirmPassword?: string | undefined;
  acceptTerms?: string | undefined;
}

export function MigrateAccountStep() {
  const { state, send } = useGetStartedMachine();

  const { formData, prefill, error } = state.context;
  const loading = state.matches({ migrateAccount: "loading" });

  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [acceptTerms, setAcceptTerms] = useState(formData.acceptTerms);
  const [marketingConsent, setMarketingConsent] = useState(formData.marketingConsent);
  const [localErrors, setLocalErrors] = useState<FormErrors>({});
  const { checks, error: passwordValidationError } = usePasswordValidation(password);
  const showPasswordMatch = confirmPassword.length > 0 && !localErrors.confirmPassword;
  const passwordsMatch = password === confirmPassword;

  const validate = (): boolean => {
    const errors: FormErrors = {};

    if (passwordValidationError) {
      errors.password = passwordValidationError;
    }

    if (password !== confirmPassword) {
      errors.confirmPassword = "Passwords do not match";
    }

    if (!acceptTerms) {
      errors.acceptTerms = "You must accept the terms of service";
    }

    setLocalErrors(errors);
    return Object.keys(errors).length === 0;
  };

  const handleSubmit = () => {
    if (!validate()) {
      return;
    }

    send({
      type: "UPDATE_FORM_DATA",
      data: { acceptTerms, marketingConsent },
    });

    send({ type: "MIGRATE", password });
  };

  const canSubmit = password && confirmPassword && acceptTerms;

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="text-center space-y-2">
        <p className="text-sm text-muted-foreground">
          {prefill?.firstName
            ? `Welcome back, ${prefill.firstName}! Set up your new portal password.`
            : "Set up your new portal password to continue."}
        </p>
      </div>

      {/* Pre-filled info display in gray disabled inputs */}
      <div className="space-y-4">
        <div className="grid grid-cols-2 gap-4">
          <div className="space-y-2">
            <Label className="text-muted-foreground">First Name</Label>
            <Input
              value={prefill?.firstName || formData.firstName || ""}
              disabled
              className="bg-muted text-muted-foreground"
            />
          </div>
          <div className="space-y-2">
            <Label className="text-muted-foreground">Last Name</Label>
            <Input
              value={prefill?.lastName || formData.lastName || ""}
              disabled
              className="bg-muted text-muted-foreground"
            />
          </div>
        </div>
        <div className="space-y-2">
          <Label className="text-muted-foreground">Email</Label>
          <Input value={formData.email} disabled className="bg-muted text-muted-foreground" />
        </div>
        {(prefill?.phone || formData.phone) && (
          <div className="space-y-2">
            <Label className="text-muted-foreground">Phone</Label>
            <Input
              value={prefill?.phone || formData.phone}
              disabled
              className="bg-muted text-muted-foreground"
            />
          </div>
        )}
        {prefill?.address && (
          <div className="space-y-2">
            <Label className="text-muted-foreground">Address</Label>
            <Input
              value={[
                prefill.address.postcode,
                prefill.address.state,
                prefill.address.city,
                prefill.address.address1,
                prefill.address.address2,
              ]
                .filter(Boolean)
                .join(", ")}
              disabled
              className="bg-muted text-muted-foreground"
            />
          </div>
        )}
      </div>

      {/* Password */}
      <div className="space-y-2">
        <Label htmlFor="password">
          Password <span className="text-danger">*</span>
        </Label>
        <PasswordInput
          id="password"
          value={password}
          onChange={e => {
            setPassword(e.target.value);
            setLocalErrors(prev => ({ ...prev, password: undefined }));
          }}
          placeholder="Create a strong password"
          disabled={loading}
          error={localErrors.password}
          autoComplete="new-password"
        />
        {localErrors.password && <p className="text-sm text-danger">{localErrors.password}</p>}
        <PasswordRequirements checks={checks} showHint={password.length === 0} />
      </div>

      {/* Confirm Password */}
      <div className="space-y-2">
        <Label htmlFor="confirmPassword">
          Confirm Password <span className="text-danger">*</span>
        </Label>
        <PasswordInput
          id="confirmPassword"
          value={confirmPassword}
          onChange={e => {
            setConfirmPassword(e.target.value);
            setLocalErrors(prev => ({ ...prev, confirmPassword: undefined }));
          }}
          placeholder="Confirm your password"
          disabled={loading}
          error={localErrors.confirmPassword}
          autoComplete="new-password"
        />
        {localErrors.confirmPassword && (
          <p className="text-sm text-danger">{localErrors.confirmPassword}</p>
        )}
        {showPasswordMatch && <PasswordMatchIndicator passwordsMatch={passwordsMatch} />}
      </div>

      {/* Terms & Marketing */}
      <div className="space-y-3">
        <div className="flex items-start gap-2">
          <Checkbox
            id="acceptTerms"
            checked={acceptTerms}
            onChange={e => {
              setAcceptTerms(e.target.checked);
              setLocalErrors(prev => ({ ...prev, acceptTerms: undefined }));
            }}
            disabled={loading}
          />
          <Label htmlFor="acceptTerms" className="text-sm font-normal leading-tight cursor-pointer">
            I accept the{" "}
            <a
              href="/terms"
              target="_blank"
              rel="noopener noreferrer"
              className="text-primary hover:underline"
            >
              Terms of Service
            </a>{" "}
            and{" "}
            <a
              href="/privacy"
              target="_blank"
              rel="noopener noreferrer"
              className="text-primary hover:underline"
            >
              Privacy Policy
            </a>{" "}
            <span className="text-danger">*</span>
          </Label>
        </div>
        {localErrors.acceptTerms && (
          <p className="text-sm text-danger ml-6">{localErrors.acceptTerms}</p>
        )}

        <div className="flex items-start gap-2">
          <Checkbox
            id="marketingConsent"
            checked={marketingConsent}
            onChange={e => setMarketingConsent(e.target.checked)}
            disabled={loading}
          />
          <Label
            htmlFor="marketingConsent"
            className="text-sm font-normal leading-tight cursor-pointer"
          >
            I would like to receive marketing emails and updates
          </Label>
        </div>
      </div>

      {/* Error display */}
      {error && (
        <div className="p-3 rounded-lg bg-danger/10 border border-danger/20">
          <p className="text-sm text-danger">{error}</p>
        </div>
      )}

      {/* Actions */}
      <div className="space-y-3">
        <Button
          type="button"
          onClick={handleSubmit}
          disabled={loading || !canSubmit}
          loading={loading}
          className="w-full h-11"
        >
          {loading ? "Setting Up Account..." : "Set Up Account"}
        </Button>

        <Button
          type="button"
          variant="ghost"
          onClick={() => send({ type: "GO_BACK" })}
          disabled={loading}
          className="w-full"
        >
          Go Back
        </Button>
      </div>
    </div>
  );
}
