"use client";
import React, { useState, useEffect } from "react";
import { DateTimePicker } from "../form/input/DateTimeInput";
import { useAuth, useProfile } from "@/hooks/auth";
import { toast } from "react-hot-toast";
import { useRouter } from "next/navigation";
import PhoneInput from "../form/group-input/PhoneInput";

interface FormData {
  firstname: string;
  lastname: string;
  phone: string;
  date_of_birth: string;
}

function isE164Phone(phone: string) {
  return /^\+[1-9]\d{7,14}$/.test(phone);
}

function isDialCodeOnly(phone: string) {
  return /^\+\d{1,4}$/.test(phone);
}

export default function OnBoardingForm() {
  const auth = useAuth();
  const { state } = auth;
  const { updateProfile, saveChanges, isUpdating } = useProfile();
  const router = useRouter();

  const [formData, setFormData] = useState<FormData>({
    firstname: "",
    lastname: "",
    phone: "+62",
    date_of_birth: "",
  });

  const [validationErrors, setValidationErrors] = useState<Record<string, string>>({});

  // no-op: editing handled locally via form state

  // Pre-fill form fields from existing user data
  useEffect(() => {
    if (state.user) {
      const profile = state.user.profile;
      const basicInfo = profile?.basic_information;
      setFormData((prev) => ({
        ...prev,
        firstname: state.user?.firstname || "",
        lastname: state.user?.lastname || "",
        phone: state.user?.phone || "+62",
        date_of_birth: basicInfo?.date_of_birth || "",
      }));
    }
  }, [state.user]);

  // Minimal local validator to replace legacy validateField from hook
  const validateFieldLocal = (path: string, value: string): string | null => {
    const trimmedValue = String(value || "").trim();

    if (path === "phone") {
      if (!trimmedValue || isDialCodeOnly(trimmedValue)) {
        return "Enter your phone number";
      }
      if (!isE164Phone(trimmedValue)) {
        return "Enter a valid phone number with country code";
      }
      return null;
    }

    const requiredPaths = new Set<string>(["firstname", "lastname", "phone"]);
    if (requiredPaths.has(path) && !trimmedValue) {
      return "This field is required";
    }
    if (path === "phone" && value.trim() && !isE164Phone(value.trim())) {
      return "Enter a valid phone number with country code";
    }
    return null;
  };

  const validateFields = (
    fields: Array<{ form: keyof FormData; profilePath?: string }>,
  ): boolean => {
    const nextErrors: Record<string, string> = {};

    fields.forEach(({ form, profilePath }) => {
      const value = formData[form];
      const error = validateFieldLocal(profilePath || form, value);
      if (error) {
        nextErrors[form] = error;
      }
    });

    setValidationErrors((prev) => ({
      ...prev,
      ...Object.fromEntries(fields.map(({ form }) => [form, ""])),
      ...nextErrors,
    }));

    return Object.keys(nextErrors).length === 0;
  };

  // Build updates object for useProfile.updateProfile from a dot path
  const buildUpdatesFromPath = (path: string, value: string): any => {
    if (!path.includes(".")) {
      return { [path]: value };
    }
    const segments = path.split(".");
    if (segments[0] !== "profile") {
      return { [path]: value };
    }
    // e.g. profile.basic_information.date_of_birth => { profile: { basic_information: { date_of_birth: value }}}
    const [, ...rest] = segments;
    let nested: any = value;
    for (let i = rest.length - 1; i >= 0; i--) {
      nested = { [rest[i]]: nested };
    }
    return { profile: nested };
  };

  const handleInputChange = (field: keyof FormData, value: string) => {
    setFormData((prev) => ({
      ...prev,
      [field]: value,
    }));

    // Update the profile hook and validate
    let profileFieldPath: string = field;
    if (field === "date_of_birth") {
      profileFieldPath = `profile.basic_information.${field}`;
    }

    updateProfile(buildUpdatesFromPath(profileFieldPath, value));

    // Validate field
    const validationError = validateFieldLocal(profileFieldPath, value);
    setValidationErrors((prev) => ({
      ...prev,
      [field]: validationError || "",
    }));
  };

  const handleSubmit = async () => {
    try {
      const isValid = validateFields([
        { form: "firstname" },
        { form: "lastname" },
        { form: "phone" },
      ]);

      if (!isValid) {
        toast.error("Please fix the validation errors");
        return;
      }

      // Save profile using the hook (this already updates context and storage)
      const success = await saveChanges();
      if (success) {
        try {
          sessionStorage.setItem("onboarding:done", "1");
        } catch {}
        router.push("/");
      } else {
        toast.error("Failed to complete profile. Please try again.");
      }
    } catch (error: any) {
      console.error("Error completing profile:", error);
      toast.error("Failed to complete profile. Please try again.");
    }
  };

  return (
    <div className="flex flex-col flex-1 lg:w-1/2 w-full">
      <div className="w-full max-w-md pt-10 mx-auto" />
      <div className="flex flex-col justify-center flex-1 w-full max-w-md mx-auto">
        <div className="mb-8">
          <h1 className="mb-2 font-semibold text-gray-800 text-title-sm dark:text-white/90 sm:text-title-md">
            Complete Your Profile
          </h1>
          <p className="text-sm text-gray-500 dark:text-gray-400">
            Complete your required account details. Date of birth is optional.
          </p>
        </div>

        <div className="mb-8 space-y-5">
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <div>
              <label
                htmlFor="firstname"
                className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"
              >
                First Name *
              </label>
              <input
                id="firstname"
                type="text"
                value={formData.firstname}
                onChange={(e) => handleInputChange("firstname", e.target.value)}
                className={`w-full px-4 py-2.5 border rounded-lg bg-transparent text-gray-800 dark:text-white placeholder:text-gray-400 dark:placeholder:text-gray-500 focus:outline-none focus:ring-3 focus:ring-brand-500/10 dark:bg-gray-900 ${
                  validationErrors.firstname
                    ? "border-red-300 dark:border-red-700 focus:border-red-300 dark:focus:border-red-700"
                    : "border-gray-300 dark:border-gray-700 focus:border-brand-300 dark:focus:border-brand-800"
                }`}
                placeholder="Enter your first name"
              />
              {validationErrors.firstname && (
                <p className="mt-1 text-sm text-red-600 dark:text-red-400">
                  {validationErrors.firstname}
                </p>
              )}
            </div>
            <div>
              <label
                htmlFor="lastname"
                className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"
              >
                Last Name *
              </label>
              <input
                id="lastname"
                type="text"
                value={formData.lastname}
                onChange={(e) => handleInputChange("lastname", e.target.value)}
                className={`w-full px-4 py-2.5 border rounded-lg bg-transparent text-gray-800 dark:text-white placeholder:text-gray-400 dark:placeholder:text-gray-500 focus:outline-none focus:ring-3 focus:ring-brand-500/10 dark:bg-gray-900 ${
                  validationErrors.lastname
                    ? "border-red-300 dark:border-red-700 focus:border-red-300 dark:focus:border-red-700"
                    : "border-gray-300 dark:border-gray-700 focus:border-brand-300 dark:focus:border-brand-800"
                }`}
                placeholder="Enter your last name"
              />
              {validationErrors.lastname && (
                <p className="mt-1 text-sm text-red-600 dark:text-red-400">
                  {validationErrors.lastname}
                </p>
              )}
            </div>
          </div>

          <div>
            <label
              htmlFor="phone"
              className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"
            >
              Phone Number *
            </label>
            {state.user?.phone ? (
              <input
                id="phone"
                type="tel"
                value={formData.phone}
                readOnly
                className="h-11 w-full cursor-not-allowed rounded-lg border border-gray-300 bg-gray-100 px-4 py-3 text-sm text-gray-500 shadow-theme-xs dark:border-gray-700 dark:bg-gray-800 dark:text-gray-400"
              />
            ) : (
              <PhoneInput
                id="phone"
                defaultValue={formData.phone}
                onChange={(value) => handleInputChange("phone", value)}
                placeholder="8123456789"
                fixedDialCode
              />
            )}
            <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
              Select your country, then enter the remaining phone number digits.
            </p>
            {validationErrors.phone && (
              <p className="mt-1 text-sm text-red-600 dark:text-red-400">
                {validationErrors.phone}
              </p>
            )}
          </div>

          <div>
            <label
              htmlFor="date_of_birth"
              className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"
            >
              Date of Birth (Optional)
            </label>
            <DateTimePicker
              mode="date"
              value={formData.date_of_birth ? new Date(formData.date_of_birth) : null}
              placeholder="Select date"
              minDate={new Date(1950, 0, 1)}
              maxDate={new Date()}
              onChange={(d: Date) => {
                if (d) {
                  const utc = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()));
                  const yyyy = utc.getUTCFullYear();
                  const mm = String(utc.getUTCMonth() + 1).padStart(2, "0");
                  const dd = String(utc.getUTCDate()).padStart(2, "0");
                  handleInputChange("date_of_birth", `${yyyy}-${mm}-${dd}`);
                }
              }}
            />
            {validationErrors.date_of_birth && (
              <p className="mt-1 text-sm text-red-600 dark:text-red-400">
                {validationErrors.date_of_birth}
              </p>
            )}
          </div>

          <div className="rounded-xl border border-gray-200 bg-gray-50 p-4 text-sm text-gray-600 dark:border-gray-800 dark:bg-gray-900 dark:text-gray-400">
            You can add more profile details later from the profile page.
          </div>
        </div>

        <div className="flex flex-col space-y-3">
          <button
            onClick={handleSubmit}
            disabled={isUpdating}
            className="flex items-center justify-center w-full px-4 py-3 text-sm font-medium text-white transition rounded-lg bg-brand-500 shadow-theme-xs hover:bg-brand-600 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {isUpdating ? "Completing..." : "Complete Profile"}
          </button>
        </div>
      </div>
    </div>
  );
}
