/**
 * CompleteAccountStep - Complete account creation after OTP verification
 *
 * Collects: Password, Phone, DOB, Gender, Terms
 * Shows pre-filled info from form step
 */

"use client";

import { useState, useCallback } from "react";
import { ArrowLeft, Check, X } from "lucide-react";
import { Button, Input, Label, ErrorMessage } from "@/components/atoms";
import { Checkbox } from "@/components/atoms/checkbox";
import { useEligibilityCheckStore } from "../../../stores/eligibility-check.store";

interface AccountFormErrors {
  password?: string;
  confirmPassword?: string;
  phone?: string;
  dateOfBirth?: string;
  gender?: string;
  acceptTerms?: string;
}

/** Helper component for password requirement indicators */
function RequirementCheck({ met, label }: { met: boolean; label: string }) {
  return (
    <div className="flex items-center gap-1">
      {met ? (
        <Check className="h-3 w-3 text-success" />
      ) : (
        <X className="h-3 w-3 text-muted-foreground" />
      )}
      <span className={met ? "text-success" : "text-muted-foreground"}>{label}</span>
    </div>
  );
}

export function CompleteAccountStep() {
  const {
    formData,
    accountData,
    updateAccountData,
    completeAccount,
    goBack,
    loading,
    error,
    clearError,
  } = useEligibilityCheckStore();

  const [accountErrors, setAccountErrors] = useState<AccountFormErrors>({});

  // Clear specific error
  const handleClearError = useCallback((field: keyof AccountFormErrors) => {
    setAccountErrors(prev => {
      const newErrors = { ...prev };
      delete newErrors[field];
      return newErrors;
    });
  }, []);

  // Password requirement checks for real-time feedback
  const passwordChecks = {
    length: accountData.password.length >= 8,
    uppercase: /[A-Z]/.test(accountData.password),
    lowercase: /[a-z]/.test(accountData.password),
    number: /[0-9]/.test(accountData.password),
  };

  // Validate password
  const validatePassword = useCallback((pass: string): string | undefined => {
    if (!pass) return "Password is required";
    if (pass.length < 8) return "Password must be at least 8 characters";
    if (!/[A-Z]/.test(pass)) return "Password must contain an uppercase letter";
    if (!/[a-z]/.test(pass)) return "Password must contain a lowercase letter";
    if (!/[0-9]/.test(pass)) return "Password must contain a number";
    return undefined;
  }, []);

  // Check if password is valid (for canSubmit)
  const isPasswordValid = validatePassword(accountData.password) === undefined;
  const doPasswordsMatch = accountData.password === accountData.confirmPassword;
  const showPasswordMatch = accountData.confirmPassword.length > 0;

  // Validate account form
  const validateAccountForm = useCallback((): boolean => {
    const errors: AccountFormErrors = {};

    const passwordError = validatePassword(accountData.password);
    if (passwordError) {
      errors.password = passwordError;
    }

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

    if (!accountData.phone.trim()) {
      errors.phone = "Phone number is required";
    }

    if (!accountData.dateOfBirth) {
      errors.dateOfBirth = "Date of birth is required";
    }

    if (!accountData.gender) {
      errors.gender = "Please select a gender";
    }

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

    setAccountErrors(errors);
    return Object.keys(errors).length === 0;
  }, [accountData]);

  const handleSubmit = async () => {
    if (!validateAccountForm()) return;
    clearError();
    await completeAccount();
  };

  const canSubmit =
    accountData.password &&
    accountData.confirmPassword &&
    accountData.phone &&
    accountData.dateOfBirth &&
    accountData.gender &&
    accountData.acceptTerms &&
    isPasswordValid &&
    doPasswordsMatch &&
    Object.keys(accountErrors).length === 0;

  return (
    <div className="space-y-6">
      {/* Pre-filled info display */}
      <div className="p-4 rounded-lg bg-muted/50 border border-border">
        <p className="text-sm text-muted-foreground mb-1">Account details:</p>
        <p className="font-medium text-foreground">
          {formData.firstName} {formData.lastName}
        </p>
        <p className="text-sm text-muted-foreground mt-1">{formData.email}</p>
        {formData.address && (
          <p className="text-sm text-muted-foreground mt-1">
            〒{formData.address.postcode} {formData.address.prefectureJa}
            {formData.address.cityJa}
            {formData.address.townJa}
            {formData.address.streetAddress}
            {formData.address.buildingName && ` ${formData.address.buildingName}`}
            {formData.address.roomNumber && ` ${formData.address.roomNumber}`}
          </p>
        )}
      </div>

      {/* Phone */}
      <div className="space-y-2">
        <Label htmlFor="phone">
          Phone Number <span className="text-danger">*</span>
        </Label>
        <Input
          id="phone"
          type="tel"
          value={accountData.phone}
          onChange={e => {
            updateAccountData({ phone: e.target.value });
            handleClearError("phone");
          }}
          placeholder="090-1234-5678"
          disabled={loading}
          error={accountErrors.phone}
        />
        <ErrorMessage>{accountErrors.phone}</ErrorMessage>
      </div>

      {/* Date of Birth */}
      <div className="space-y-2">
        <Label htmlFor="dateOfBirth">
          Date of Birth <span className="text-danger">*</span>
        </Label>
        <Input
          id="dateOfBirth"
          type="date"
          value={accountData.dateOfBirth}
          onChange={e => {
            updateAccountData({ dateOfBirth: e.target.value });
            handleClearError("dateOfBirth");
          }}
          disabled={loading}
          error={accountErrors.dateOfBirth}
          max={new Date().toISOString().split("T")[0]}
        />
        <ErrorMessage>{accountErrors.dateOfBirth}</ErrorMessage>
      </div>

      {/* Gender */}
      <div className="space-y-2">
        <Label>
          Gender <span className="text-danger">*</span>
        </Label>
        <div className="flex gap-4">
          {(["male", "female", "other"] as const).map(option => (
            <label key={option} className="flex items-center gap-2 cursor-pointer">
              <input
                type="radio"
                name="gender"
                value={option}
                checked={accountData.gender === option}
                onChange={() => {
                  updateAccountData({ gender: option });
                  handleClearError("gender");
                }}
                disabled={loading}
                className="h-4 w-4 text-primary focus:ring-primary"
              />
              <span className="text-sm capitalize">{option}</span>
            </label>
          ))}
        </div>
        <ErrorMessage>{accountErrors.gender}</ErrorMessage>
      </div>

      {/* Password */}
      <div className="space-y-2">
        <Label htmlFor="password">
          Password <span className="text-danger">*</span>
        </Label>
        <Input
          id="password"
          type="password"
          value={accountData.password}
          onChange={e => {
            updateAccountData({ password: e.target.value });
            handleClearError("password");
          }}
          placeholder="Create a strong password"
          disabled={loading}
          error={accountErrors.password}
          autoComplete="new-password"
        />
        <ErrorMessage>{accountErrors.password}</ErrorMessage>
        {/* Real-time password requirements */}
        {accountData.password.length > 0 && (
          <div className="grid grid-cols-2 gap-1 text-xs">
            <RequirementCheck met={passwordChecks.length} label="8+ characters" />
            <RequirementCheck met={passwordChecks.uppercase} label="Uppercase letter" />
            <RequirementCheck met={passwordChecks.lowercase} label="Lowercase letter" />
            <RequirementCheck met={passwordChecks.number} label="Number" />
          </div>
        )}
        {accountData.password.length === 0 && (
          <p className="text-xs text-muted-foreground">
            At least 8 characters with uppercase, lowercase, and numbers
          </p>
        )}
      </div>

      {/* Confirm Password */}
      <div className="space-y-2">
        <Label htmlFor="confirmPassword">
          Confirm Password <span className="text-danger">*</span>
        </Label>
        <Input
          id="confirmPassword"
          type="password"
          value={accountData.confirmPassword}
          onChange={e => {
            updateAccountData({ confirmPassword: e.target.value });
            handleClearError("confirmPassword");
          }}
          placeholder="Confirm your password"
          disabled={loading}
          error={accountErrors.confirmPassword}
          autoComplete="new-password"
        />
        <ErrorMessage>{accountErrors.confirmPassword}</ErrorMessage>
        {/* Real-time password match indicator */}
        {showPasswordMatch && !accountErrors.confirmPassword && (
          <div className="flex items-center gap-1 text-xs">
            {doPasswordsMatch ? (
              <>
                <Check className="h-3 w-3 text-success" />
                <span className="text-success">Passwords match</span>
              </>
            ) : (
              <>
                <X className="h-3 w-3 text-danger" />
                <span className="text-danger">Passwords do not match</span>
              </>
            )}
          </div>
        )}
      </div>

      {/* Terms & Marketing */}
      <div className="space-y-3">
        <div className="flex items-start gap-2">
          <Checkbox
            id="acceptTerms"
            checked={accountData.acceptTerms}
            onChange={e => {
              updateAccountData({ acceptTerms: e.target.checked });
              handleClearError("acceptTerms");
            }}
            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>
        <ErrorMessage className="ml-6">{accountErrors.acceptTerms}</ErrorMessage>

        <div className="flex items-start gap-2">
          <Checkbox
            id="marketingConsent"
            checked={accountData.marketingConsent}
            onChange={e => updateAccountData({ marketingConsent: 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>

      {/* API Error */}
      {error && (
        <div className="p-4 rounded-lg bg-danger/10 border border-danger/20">
          <ErrorMessage showIcon>{error}</ErrorMessage>
        </div>
      )}

      {/* Actions */}
      <div className="space-y-3">
        <Button
          type="button"
          onClick={handleSubmit}
          disabled={loading || !canSubmit}
          loading={loading}
          loadingText="Creating Account..."
          className="w-full"
        >
          Create Account
        </Button>

        <Button
          type="button"
          variant="ghost"
          onClick={goBack}
          disabled={loading}
          leftIcon={<ArrowLeft className="h-4 w-4" />}
          className="w-full"
        >
          Go Back
        </Button>
      </div>
    </div>
  );
}
