"use client";

import React, { useRef, useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { submitEnquiryFormData } from "@/services/enquiry-form.service";
import ReCAPTCHA from "react-google-recaptcha";

type OptionField = {
  label: string;
  value: string;
};

type Field =
  | {
    name: string;
    label: string;
    type: "text" | "email" | "tel" | "textarea";
    required: boolean;
    placeholder?: string | null;
  }
  | {
    name: string;
    label: string;
    type: "select";
    required: boolean;
    placeholder?: string | null;
    options: {
      multiSelect: boolean;
      optionFields: OptionField[];
    };
  };


interface EnquiryFormProps {
  fields: Field[];
  // formId: string;
}

export default function EnquiryForm({ fields }: EnquiryFormProps) {

  const [formValues, setFormValues] = useState<Record<string, string>>(
    fields.reduce((acc, f) => {
      if (f.type === "select" && f.options.optionFields.length > 0) {
        acc[f.name] = f.options.optionFields[0].value;
      } else {
        acc[f.name] = "";
      }
      return acc;
    }, {} as Record<string, string>)
  );

  const [captchaToken, setCaptchaToken] = useState<string | null>(null);
  const recaptchaRef = useRef<ReCAPTCHA>(null);
  const [isFormSubmitted, setIsFormSubmitted] = useState(false);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);

  const handleChange = (
    e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
  ) => {
    const { id, value } = e.target;
    setFormValues((prev) => ({ ...prev, [id]: value }));
  };

  const handleSelectChange = (name: string, value: string) => {
    setFormValues((prev) => ({ ...prev, [name]: value }));
  };

  const handleCaptchaChange = (token: string | null) => {
    setCaptchaToken(token);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsFormSubmitted(false);
    setErrorMessage(null);

    if (!captchaToken) {
      setErrorMessage("Please verify that you are not a robot.");
      return;
    }

    const phoneField = fields.find((f) => f.type === "tel");
    if (phoneField) {
      const phoneValue = formValues[phoneField.name];
      const phoneRegex = /^[0-9]{10}$/;

      if (!phoneRegex.test(phoneValue)) {
        setErrorMessage("Please enter a valid 10-digit phone number.");
        return;
      }
    }

    try {
      await submitEnquiryFormData("b9def00a-c5a8-46c2-ab8a-c0701f3f3c6b", formValues);
      const resetValues = fields.reduce((acc, f) => {
        if (f.type === "select" && f.options.optionFields.length > 0) {
          acc[f.name] = f.options.optionFields[0].value;
        } else {
          acc[f.name] = "";
        }
        return acc;
      }, {} as Record<string, string>);

      setFormValues(resetValues);
      recaptchaRef.current?.reset();
      setCaptchaToken(null);
      setIsFormSubmitted(true);
      // setErrorMessage(null);

      // alert("Enquiry submitted successfully!");
    } catch (error) {
      console.error("Submit failed:", error);
      setErrorMessage("Something went wrong. Please try again.");
    }
  };

  return (
    <form onSubmit={handleSubmit} className="grid gap-6">
      {fields.map((field, idx) => (
        <div className="grid gap-1" key={idx}>
          <Label htmlFor={field.name} className="text-gray-700 text-[16px] font-normal">
            {field.label}
            {"required" in field && field.required && (
              <span className="text-red-500 text-[15px]">*</span>
            )}
          </Label>

          {field.type === "select" && (
            <Select
              onValueChange={(val) => handleSelectChange(field.name, val)}
              value={formValues[field.name]}
            >
              <SelectTrigger
                id={field.name}
                className="w-full rounded-sm border-[#b6b6b6]  text-[15px]"
              >
                <SelectValue
                  placeholder={field.placeholder ?? `Select ${field.label}`}
                />
              </SelectTrigger>
              <SelectContent>
                {field.options.optionFields.map((opt, i) => (
                  <SelectItem key={i} value={opt.value}>
                    {opt.label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          )}

          {field.type === "textarea" && (
            <Textarea
              id={field.name}
              rows={4}
              value={formValues[field.name]}
              onChange={handleChange}
              required={field.required}
              className="rounded-sm border-[#b6b6b6]"
            />
          )}

          {(field.type === "text" ||
            field.type === "email" ||
            field.type === "tel") && (
              <Input
                id={field.name}
                type={field.type}
                value={formValues[field.name]}
                onChange={handleChange}
                required={field.required}
                className="rounded-sm border-[#b6b6b6]"
              />
            )}
        </div>
      ))}

      <div className="mt-2">
        <ReCAPTCHA
          ref={recaptchaRef}
          sitekey={"6Lc2ovgrAAAAAMgsLRT0MuELe9PwAhxti6bCcV3l"}
          onChange={handleCaptchaChange}
        />
      </div>
      {errorMessage && (
        <p className="text-red-600 text-sm mt-2">{errorMessage}</p>
      )}

      <Button
        type="submit"
        className="w-fit bg-[#f7931e] hover:bg-[#e0841a] text-white py-2 px-8 rounded-sm"
      >
        Send
      </Button>
      {isFormSubmitted && (
        <p className="text-green-600 text-sm mt-2">Enquiry submitted successfully!</p>
      )}
    </form>
  );
}
