"use client";

import React, { useState, useEffect } from "react";
// types.ts veya OfferFormModal.tsx içinde
export interface OfferItem {
  id: string;
  title: string;
  brand: string;
  category: string;
  quantity: number;
}

export interface OfferFormModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSubmit: (formData: {
    name: string;
    email: string;
    telefon: string;
    mesaj: string;
    token: string; // reCAPTCHA token
    offerItems: OfferItem[]; // modal'dan gönderilen ürünler
  }) => void;
  offerItems: OfferItem[]; // required prop: favorites page'den gelen ürünler
}

const OfferFormModal: React.FC<OfferFormModalProps> = ({ isOpen, onClose, onSubmit, offerItems }) => {
  const [form, setForm] = useState({ name: "", email: "", telefon: "", mesaj: "" });
  const [isLoading, setIsLoading] = useState(false);
  const [isRecaptchaVerified, setIsRecaptchaVerified] = useState(false);
  const [recaptchaToken, setRecaptchaToken] = useState("");
  const [isRecaptchaReady, setIsRecaptchaReady] = useState(false);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    setForm({ ...form, [e.target.name]: e.target.value });
  };

  // reCAPTCHA render
  useEffect(() => {
    if (!isOpen) return;

    const renderRecaptcha = () => {
      if (!(window as any).grecaptcha || document.querySelector("#offer-recaptcha iframe")) {
        return;
      }

      (window as any).grecaptcha.render("offer-recaptcha", {
        sitekey: process.env.NEXT_PUBLIC_RECAPTCHA_SITE_KEY,
        callback: (token: string) => {
          setRecaptchaToken(token);
          setIsRecaptchaVerified(true);
        },
      });
      setIsRecaptchaReady(true);
    };

    if ((window as any).grecaptcha) {
      renderRecaptcha();
      return;
    }

    const existingScript = document.querySelector(
      'script[src*="recaptcha/api.js"]'
    ) as HTMLScriptElement | null;

    const handleScriptLoad = () => renderRecaptcha();

    if (existingScript) {
      existingScript.addEventListener("load", handleScriptLoad, { once: true });
      return () => {
        existingScript.removeEventListener("load", handleScriptLoad);
      };
    }

    const script = document.createElement("script");
    script.src = "https://www.google.com/recaptcha/api.js";
    script.async = true;
    script.defer = true;
    script.onload = handleScriptLoad;
    document.head.appendChild(script);

    return () => {
      script.onload = null;
    };
  }, [isOpen]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!isRecaptchaVerified) {
      alert("Lütfen reCAPTCHA doğrulamasını tamamlayın!");
      return;
    }

    setIsLoading(true);

    await onSubmit({
      ...form,
      token: recaptchaToken,
      offerItems, // favorites page’den gelen ürünler
    });

    setIsLoading(false);
    onClose();

    // reCAPTCHA reset
    (window as any).grecaptcha.reset();
    setRecaptchaToken("");
    setIsRecaptchaVerified(false);
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
      <div className="bg-white w-full max-w-md p-6 rounded shadow-lg relative overflow-visible">
        <button
          className="absolute top-2 right-2 text-white bg-black px-3 py-3 hover:text-gray-300 font-bold"
          onClick={onClose}
        >
          X
        </button>

        <h2 className="text-xl font-semibold mb-4">Teklif Gönder</h2>

        <form className="flex flex-col gap-3" onSubmit={handleSubmit}>
          <input
            type="text"
            name="name"
            placeholder="Adınız"
            className="input"
            value={form.name}
            onChange={handleChange}
            required
          />
          <input
            type="email"
            name="email"
            placeholder="E-mail"
            className="input"
            value={form.email}
            onChange={handleChange}
            required
          />
          <input
            type="text"
            name="telefon"
            placeholder="Telefon"
            className="input"
            value={form.telefon}
            onChange={handleChange}
          />
          <textarea
            name="mesaj"
            rows={4}
            placeholder="Açıklama"
            className="input resize-none"
            value={form.mesaj}
            onChange={handleChange}
          ></textarea>

          <div id="offer-recaptcha" className="my-2 min-h-[78px]"></div>

          <button
            type="submit"
            disabled={!isRecaptchaVerified || isLoading || !isRecaptchaReady}
            className={`px-4 py-2 bg-primary text-white rounded font-semibold ${
              !isRecaptchaVerified || isLoading || !isRecaptchaReady
                ? "opacity-50 cursor-not-allowed"
                : "hover:bg-primary/80"
            }`}
          >
            {isLoading ? "Gönderiliyor..." : "Gönder"}
          </button>
        </form>
      </div>
    </div>
  );
};

export default OfferFormModal;
