"use client";
import React, { useState } from "react";
import { toast } from "react-hot-toast";
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faWhatsapp } from '@fortawesome/free-brands-svg-icons';
interface CreditCardApplication {
  name: string;
  email: string;
  phone: string; // stores only 9 digits after +971
  salary: number;
  agree: boolean;
}

const CreditCardApplyForm: React.FC<{
  cardId: number;
  cardName: string;
  onSuccess: () => void;
}> = ({ cardId, cardName, onSuccess }) => {
  const [form, setForm] = useState<CreditCardApplication>({
    name: "",
    email: "",
    phone: "",
    salary: 0,
    agree: false,
  });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // State for WhatsApp toggle
  const [enabled, setEnabled] = useState(true);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value, type, checked } = e.target;

    if (name === "phone") {
      // allow only digits and max 9 digits
      const digitsOnly = value.replace(/\D/g, "").slice(0, 9);
      setForm((prev) => ({ ...prev, phone: digitsOnly }));
    } else {
      setForm((prev) => ({
        ...prev,
        [name]: type === "checkbox" ? checked : type === "number" ? Number(value) : value,
      }));
    }
  };

  const validate = (): boolean => {
    if (!form.name) return setError("Name is required"), false;
    if (!form.email || !/\S+@\S+\.\S+/.test(form.email)) return setError("Valid email required"), false;
    if (!form.phone || form.phone.length !== 9)
      return setError("Enter a valid 9-digit mobile number"), false;
    if (form.salary <= 0) return setError("Enter valid salary"), false;
    if (!form.agree) return setError("Please accept the terms"), false;
    setError(null);
    return true;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!validate()) return;

    setLoading(true);
    try {
      const res = await fetch(`/api/applycard/${cardId}`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        // prepend +971 here
        body: JSON.stringify({ ...form, phone: "+971" + form.phone, cardId }),
      });

      const data = await res.json();

      if (!res.ok) {
        toast.error(data.error || "Submission failed");
      } else {
        toast.success("Application submitted");

        await fetch("/api/sendmail", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            name: form.name,
            email: form.email,
            phone: "+971" + form.phone,
            salary: form.salary,
            cardId,
            cardName,
          }),
        });

        setForm({ name: "", email: "", phone: "", salary: 0, agree: false });
        onSuccess();
      }
    } catch (err) {
      toast.error(`Unexpected error. Try again .${ err}`);
    } finally {
      setLoading(false);
    }
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-3 text-sm">
      <h2 className="text-md font-semibold text-blue-800 mb-4">
        Please fill up your details for quick & secure processing
      </h2>
      {error && <p className="text-red-600">{error}</p>}

      {/* Name Field */}
      <div>
        <label htmlFor="name" className="block text-sm font-medium text-gray-700 hidden sm:block">
          Name
        </label>
        <div className="relative">
          <span className="absolute left-2 top-1/2 -translate-y-1/2 text-gray-400">👤</span>
          <input
            id="name"
            name="name"
            type="text"
            placeholder="Name"
            value={form.name}
            onChange={handleChange}
            className="w-full pl-8 pr-3 py-1 border rounded text-sm sm:text-base"
          />
        </div>
      </div>

      {/* Email Field */}
      <div>
        <label htmlFor="email" className="block text-sm font-medium text-gray-700 hidden sm:block">
          Email
        </label>
        <div className="relative">
          <span className="absolute left-2 top-1/2 -translate-y-1/2 text-gray-400">📧</span>
          <input
            id="email"
            name="email"
            type="email"
            placeholder="Email"
            value={form.email}
            onChange={handleChange}
            className="w-full pl-8 pr-3 py-1 border rounded text-sm sm:text-base"
          />
        </div>
      </div>

      {/* Phone Field with +971 prefix */}
      <div>
        <label
          htmlFor="phone"
          className="block text-sm font-medium text-gray-700 hidden sm:block"
        >
          Mobile Number
        </label>
        <div className="relative">
          <span className="absolute left-2 top-1/2 -translate-y-1/2 text-gray-500 select-none">+971</span>
          <span className="absolute left-14 top-1/2 -translate-y-1/2 pointer-events-none">
            {/* Colored iPhone SVG icon */}
            <svg
              xmlns="http://www.w3.org/2000/svg"
              className="h-5 w-5"
              viewBox="0 0 24 24"
              fill="#3b82f6"
              stroke="none"
            >
              <rect x="7" y="2" width="10" height="20" rx="3" ry="3" />
              <rect x="10" y="19" width="4" height="1.5" rx="0.75" ry="0.75" fill="#2563eb" />
              <circle cx="12" cy="4" r="1" fill="#60a5fa" />
            </svg>
          </span>

          <input
            id="phone"
            name="phone"
            type="tel"
            placeholder="Enter mobile number"
            value={form.phone}
            onChange={handleChange}
            className="w-full pl-32 pr-3 py-2 border rounded text-sm sm:text-base text-left"
          />
        </div>
      </div>

      {/* Salary Field */}
      <div>
        <label
          htmlFor="salary"
          className="block text-sm font-medium text-gray-700 hidden sm:block"
        >
          Salary
        </label>
        <div className="relative">
          <span className="absolute left-2 top-1/2 -translate-y-1/2 text-gray-500 select-none">AED</span>
          <input
            id="salary"
            name="salary"
            type="number"
            placeholder="     Salary (AED)"
         value={form.salary === 0 ? "" : form.salary}
            onChange={handleChange}
            className="w-full pl-8 pr-3 py-1 border rounded text-sm sm:text-base"
          />
        </div>
      </div>

      {/* Checkbox with top alignment */}
  <label className="flex items-start gap-2 text-sm">
  <input
    type="checkbox"
    name="agree"
    checked={form.agree}
    onChange={handleChange}
    className="mt-1 w-4 h-4 shrink-0"
  />
  <span className="text-gray-500 text-xs">
    I agree to the website  
    <a href="/TermsOfUse" target="_blank" className="text-blue-600 underline"> privacy policies & terms of uses </a>. I authorize 
     www.Banksfinders.com (B F Fintech Commercial Brokers LLC) to share my personal details with banks registered in UAE.
  </span>
</label>

{/* WhatsApp toggle row */}
{/* WhatsApp toggle row */}
<div className="flex items-center justify-between mt-4 mb-4">
  <div className="flex items-center gap-2">
    {/* Smaller cleaner WhatsApp icon */}
   <FontAwesomeIcon icon={faWhatsapp}  className="text-green-500 h-6 hover:bg-green-600 transition"/>

    <label htmlFor="whatsappToggle" className="text-sm font-medium text-gray-700 cursor-pointer">
      Get update on WhatsApp
    </label>
  </div>

  <button
    id="whatsappToggle"
    type="button"
    onClick={() => setEnabled(!enabled)}
    aria-pressed={enabled}
    className={`relative inline-flex items-center h-6 rounded-full w-11 focus:outline-none focus:ring-2 focus:ring-offset-2 ${
      enabled ? "bg-green-600" : "bg-gray-300"
    } transition-colors duration-300`}
  >
    <span
      className={`inline-block w-5 h-5 bg-white rounded-full shadow transform transition-transform duration-300 ${
        enabled ? "translate-x-5" : "translate-x-0"
      }`}
    />
  </button>
</div>


      {/* Submit Button */}
      <button
        type="submit"
        disabled={loading}
        className="w-full py-2 px-4 bg-blue-600 text-white rounded hover:bg-blue-700 text-sm"
      >
        {loading ? "Submitting..." : "Apply Now"}
      </button>
    </form>
  );
};

export default CreditCardApplyForm;
