/**
 * FormStep - Initial form for eligibility check
 *
 * Collects: Name, Email, Address
 * Two buttons: "Create Account & Submit" (primary) and "Just Submit Request" (secondary)
 */

"use client";

import { useState, useCallback, useMemo } from "react";
import { UserPlus, ArrowRight } from "lucide-react";
import { Button, Input, Label, ErrorMessage } from "@/components/atoms";
import {
  JapanAddressForm,
  type JapanAddressFormData,
} from "@/features/address/components/JapanAddressForm";
import { useEligibilityCheckStore } from "../../../stores/eligibility-check.store";

interface FormErrors {
  firstName?: string;
  lastName?: string;
  email?: string;
  address?: string;
}

export function FormStep() {
  const {
    formData,
    updateFormData,
    setAddressComplete,
    isAddressComplete,
    submitOnly,
    submitAndCreate,
    loading,
    submitType,
    error,
    clearError,
  } = useEligibilityCheckStore();

  const [formErrors, setFormErrors] = useState<FormErrors>({});

  // Validate email format
  const isValidEmail = (email: string): boolean => {
    return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
  };

  // Check if name and email are complete (for enabling buttons when address is done)
  const isNameEmailComplete = useMemo(() => {
    const hasName = formData.firstName.trim() && formData.lastName.trim();
    const hasEmail = formData.email.trim() && isValidEmail(formData.email);
    return hasName && hasEmail;
  }, [formData.firstName, formData.lastName, formData.email]);

  // Validate form
  const validateForm = useCallback((): boolean => {
    const errors: FormErrors = {};

    if (!formData.firstName.trim()) {
      errors.firstName = "First name is required";
    }
    if (!formData.lastName.trim()) {
      errors.lastName = "Last name is required";
    }
    if (!formData.email.trim()) {
      errors.email = "Email is required";
    } else if (!isValidEmail(formData.email)) {
      errors.email = "Enter a valid email address";
    }
    if (!isAddressComplete) {
      errors.address = "Please complete the address";
    }

    setFormErrors(errors);
    return Object.keys(errors).length === 0;
  }, [formData, isAddressComplete]);

  // Clear specific form error
  const handleClearFormError = useCallback((field: keyof FormErrors) => {
    setFormErrors(prev => {
      const newErrors = { ...prev };
      delete newErrors[field];
      return newErrors;
    });
  }, []);

  // Handle address form changes
  const handleAddressChange = useCallback(
    (data: JapanAddressFormData, isComplete: boolean) => {
      updateFormData({ address: data });
      setAddressComplete(isComplete);
      if (isComplete) {
        handleClearFormError("address");
      }
    },
    [updateFormData, setAddressComplete, handleClearFormError]
  );

  // Handle "Just Submit Request" (secondary action)
  const handleSubmitOnly = async () => {
    if (!validateForm()) return;
    clearError();
    await submitOnly();
  };

  // Handle "Create Account & Submit" (primary action)
  const handleSubmitAndCreate = async () => {
    if (!validateForm()) return;
    clearError();
    await submitAndCreate();
  };

  return (
    <div className="space-y-6">
      {/* Name fields */}
      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
        <div className="space-y-2">
          <Label htmlFor="firstName">
            First Name <span className="text-danger">*</span>
          </Label>
          <Input
            id="firstName"
            value={formData.firstName}
            onChange={e => {
              updateFormData({ firstName: e.target.value });
              handleClearFormError("firstName");
            }}
            placeholder="Taro"
            disabled={loading}
            error={formErrors.firstName}
          />
          <ErrorMessage>{formErrors.firstName}</ErrorMessage>
        </div>

        <div className="space-y-2">
          <Label htmlFor="lastName">
            Last Name <span className="text-danger">*</span>
          </Label>
          <Input
            id="lastName"
            value={formData.lastName}
            onChange={e => {
              updateFormData({ lastName: e.target.value });
              handleClearFormError("lastName");
            }}
            placeholder="Yamada"
            disabled={loading}
            error={formErrors.lastName}
          />
          <ErrorMessage>{formErrors.lastName}</ErrorMessage>
        </div>
      </div>

      {/* Email */}
      <div className="space-y-2">
        <Label htmlFor="email">
          Email <span className="text-danger">*</span>
        </Label>
        <Input
          id="email"
          type="email"
          value={formData.email}
          onChange={e => {
            updateFormData({ email: e.target.value });
            handleClearFormError("email");
          }}
          placeholder="your@email.com"
          disabled={loading}
          error={formErrors.email}
        />
        {!formErrors.email && (
          <p className="text-xs text-muted-foreground">
            We&apos;ll send availability results to this email
          </p>
        )}
        <ErrorMessage>{formErrors.email}</ErrorMessage>
      </div>

      {/* Address */}
      <div className="space-y-2">
        <Label>
          Installation Address <span className="text-danger">*</span>
        </Label>
        <JapanAddressForm
          onChange={handleAddressChange}
          disabled={loading}
          completionContent={
            <div className="space-y-3 pt-2">
              {/* API Error */}
              {error && (
                <div className="p-3 rounded-lg bg-danger/10 border border-danger/20">
                  <ErrorMessage showIcon>{error}</ErrorMessage>
                </div>
              )}

              {/* Validation message - shown when name/email incomplete */}
              {!isNameEmailComplete && (
                <p className="text-sm text-warning text-center">
                  Please complete your name and email above
                </p>
              )}

              {/* Action buttons - always clickable, validation on click */}
              <Button
                type="button"
                onClick={handleSubmitAndCreate}
                disabled={loading}
                loading={loading && submitType === "create"}
                leftIcon={<UserPlus className="h-4 w-4" />}
                className="w-full"
              >
                Create Account & Submit
              </Button>
              <p className="text-xs text-muted-foreground text-center">
                Recommended — Get faster service and track your request
              </p>

              <div className="relative flex items-center py-1">
                <div className="flex-grow border-t border-border/50" />
                <span className="px-2 text-xs text-muted-foreground">or</span>
                <div className="flex-grow border-t border-border/50" />
              </div>

              <Button
                type="button"
                variant="secondary"
                onClick={handleSubmitOnly}
                disabled={loading}
                loading={loading && submitType === "check"}
                leftIcon={<ArrowRight className="h-4 w-4" />}
                className="w-full"
              >
                Just Submit Request
              </Button>
            </div>
          }
        />
        <ErrorMessage>{formErrors.address}</ErrorMessage>
      </div>
    </div>
  );
}
