"use client";

import { useState } from "react";
import { SelectedSlot, SelectedStore, UserDetails } from "./AppointmentPage";
import { toast } from "sonner";

interface Props {
  selectedStore: SelectedStore;
  selectedSlot: SelectedSlot;
  onSubmit: (details: UserDetails) => void;
  onEditStore: () => void;
  onEditSlot: () => void;
}

export default function StepEnterDetails({
  selectedStore,
  selectedSlot,
  onSubmit,
  onEditStore,
  onEditSlot,
}: Props) {
  const [form, setForm] = useState<UserDetails>({
    name: "",
    phone: "",
    email: "",
    celebrating: "groom",
    lookingFor: "",
  });

  const [validationError, setValidationError] = useState<any>({
    phone: "",
    email: "",
    name: "",
    lookingFor: "",
  });

  const [touched, setTouched] = useState({
    name: false,
    phone: false,
    email: false,
    lookingFor: false,
  });

  const checkValidation = (key: string, value: any) => {
    let error = null;

    switch (key) {
      case "phone": {
        if (!value) {
          error = "Phone Number is required";
        } else {
          // Indian phone number: starts with 6-9 and has 10 digits
          const phoneRegex = /^[6-9]\d{9}$/;
          if (!phoneRegex.test(value)) {
            error = "Invalid Indian phone number";
          }
        }
        break;
      }

      case "email": {
        if (!value) {
          error = "Email is required";
        } else {
          // Standard email regex
          const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
          if (!emailRegex.test(value)) {
            error = "Invalid email address";
          }
        }
        break;
      }

      case "name": {
        if (!value) {
          error = "Name is required";
        } else {
          const usernameRegex = /^[A-Za-z][A-Za-z0-9_ ]{2,23}$/;
          if (value.length < 3 || value.length > 20) {
            error = "Username must be 3–25 characters";
          } else if (!usernameRegex.test(value)) {
            error =
              "Name must start with a letter and contain only letters, numbers, and _";
          }
        }
        break;
      }

      case "lookingFor": {
        if (!value || value.trim() === "") {
          error = "Please tell us what you're looking for";
        } else if (value.length < 10) {
          error = "Please provide more details (minimum 10 characters)";
        } else if (value.length > 500) {
          error = "Description must be less than 500 characters";
        }
        break;
      }

      default:
        error = null;
    }

    setValidationError((prev: any) => ({
      ...prev,
      [key]: error,
    }));

    return error;
  };

  const handleFieldChange = (key: string, value: any) => {
    setForm({ ...form, [key]: value });
    setTouched((prev) => ({ ...prev, [key]: true }));
    checkValidation(key, value);
  };

  const handleBlur = (key: string) => {
    setTouched((prev) => ({ ...prev, [key]: true }));
    checkValidation(key, form[key as keyof UserDetails]);
  };

  const validateAllFields = () => {
    const errors: any = {};
    let hasError = false;

    // Validate each field
    const fields = [
      { key: "name", label: "Name" },
      { key: "phone", label: "Phone Number" },
      { key: "email", label: "Email" },
      { key: "lookingFor", label: "Looking For" },
    ];

    fields.forEach(({ key }) => {
      const value = form[key as keyof UserDetails];
      const error = checkValidation(key, value);
      if (error) {
        errors[key] = error;
        hasError = true;
      }
      setTouched((prev) => ({ ...prev, [key]: true }));
    });

    setValidationError((prev: any) => ({
      ...prev,
      ...errors,
    }));

    return hasError;
  };

  const handleSubmit = () => {
    const hasError = validateAllFields();

    if (hasError) {
      toast.error("Please fill all required fields correctly");
      return;
    }

    onSubmit(form);
  };

  return (
    <div className="space-y-5 rounded-xl border bg-white p-6">
      <h2 className="text-xl font-medium">Enter Details</h2>

      {/* NAME */}
      <div className="space-y-1">
        <input
          placeholder="Name*"
          className={`w-full rounded border p-3 transition-colors ${
            touched.name && validationError?.name
              ? "border-red-500 focus:border-red-500 focus:ring-red-500"
              : "border-gray-300 focus:border-blue-500"
          }`}
          value={form.name}
          onChange={(e) => handleFieldChange("name", e.target.value)}
          onBlur={() => handleBlur("name")}
        />
        {touched.name && validationError?.name && (
          <span className="text-sm text-red-500">{validationError.name}</span>
        )}
      </div>

      {/* PHONE */}
      <div className="space-y-1">
        <input
          type="tel"
          inputMode="numeric"
          pattern="[0-9]*"
          placeholder="Mobile number*"
          className={`w-full rounded border p-3 transition-colors ${
            touched.phone && validationError?.phone
              ? "border-red-500 focus:border-red-500 focus:ring-red-500"
              : "border-gray-300 focus:border-blue-500"
          }`}
          maxLength={10}
          value={form.phone}
          onChange={(e) => {
            const phone = e.target.value.replace(/\D/g, "");
            handleFieldChange("phone", phone);
          }}
          onBlur={() => handleBlur("phone")}
        />
        {touched.phone && validationError?.phone && (
          <span className="text-sm text-red-500">{validationError.phone}</span>
        )}
      </div>

      {/* EMAIL */}
      <div className="space-y-1">
        <input
          type="email"
          placeholder="Email ID*"
          className={`w-full rounded border p-3 transition-colors ${
            touched.email && validationError?.email
              ? "border-red-500 focus:border-red-500 focus:ring-red-500"
              : "border-gray-300 focus:border-blue-500"
          }`}
          value={form.email}
          onChange={(e) => handleFieldChange("email", e.target.value)}
          onBlur={() => handleBlur("email")}
        />
        {touched.email && validationError?.email && (
          <span className="text-sm text-red-500">{validationError.email}</span>
        )}
      </div>

      {/* CELEBRATION */}
      <div className="space-y-2">
        <p className="font-medium">What are you celebrating?</p>

        {["groom", "event", "other"].map((item) => (
          <label key={item} className="flex items-center gap-2">
            <input
              type="radio"
              checked={form.celebrating === item}
              name="celebrating"
              onChange={() =>
                setForm({
                  ...form,
                  celebrating: item as any,
                })
              }
            />
            {item === "groom" && "I am a Groom"}
            {item === "event" && "Attending an Event"}
            {item === "other" && "Other"}
          </label>
        ))}
      </div>

      {/* LOOKING FOR */}
      <div className="space-y-1">
        <textarea
          placeholder="What are you looking for?*"
          className={`w-full rounded border p-3 transition-colors ${
            touched.lookingFor && validationError?.lookingFor
              ? "border-red-500 focus:border-red-500 focus:ring-red-500"
              : "border-gray-300 focus:border-blue-500"
          }`}
          rows={4}
          value={form.lookingFor}
          onChange={(e) => handleFieldChange("lookingFor", e.target.value)}
          onBlur={() => handleBlur("lookingFor")}
        />
        {touched.lookingFor && validationError?.lookingFor && (
          <span className="text-sm text-red-500">
            {validationError.lookingFor}
          </span>
        )}
      </div>

      {/* SUBMIT */}
      <button
        onClick={handleSubmit}
        className="w-full rounded bg-[rgba(var(--primary),1)] py-3 text-white transition-colors hover:bg-[rgba(var(--primary),0.9)]"
      >
        Confirm Appointment
      </button>
    </div>
  );
}
