"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 LoanApplication {
  name: string;
  email: string;
  phone: string;
  salary: number;
  agree: boolean;
}

interface BankLoanApplyFormProps {
  loanId: number;
  loanName: string;
  bankName: string;
  onSuccess: () => void;
}

const BankLoanApplyForm: React.FC<BankLoanApplyFormProps> = ({
  loanId,
  loanName,
  bankName,
  onSuccess,
}) => {
  const [form, setForm] = useState<LoanApplication>({
    name: "",
    email: "",
    phone: "",
    salary: 0,
    agree: false,
  });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [enableWhatsApp, setEnableWhatsApp] = useState(true);

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

    if (name === "phone") {
      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 payload = { ...form, phone: "+971" + form.phone, loanName, bankName, agree: form.agree };

      const res = await fetch(`/api/applyloan/${loanId}`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });

      const data = await res.json();

      if (!res.ok) {
        toast.error(data.error || "Submission failed");
        return;
      }

      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,
          loanId,
          loanName,
          bankName,
          productType: "loan",
        }),
      });

      setForm({ name: "", email: "", phone: "", salary: 0, agree: false });
      onSuccess();
    } catch (err) {
      toast.error(`Unexpected error. Try again. ${err instanceof Error ? err.message : 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>}

      <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>

      <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>

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

      <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>

      <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>

      <div className="flex items-center justify-between mt-4 mb-4">
        <div className="flex items-center gap-2">
          <FontAwesomeIcon icon={faWhatsapp} className="text-green-500 h-6" />
          <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={() => setEnableWhatsApp(!enableWhatsApp)}
          aria-pressed={enableWhatsApp}
          className={`relative inline-flex items-center h-6 rounded-full w-11 focus:outline-none focus:ring-2 focus:ring-offset-2 ${
            enableWhatsApp ? "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 ${
              enableWhatsApp ? "translate-x-5" : "translate-x-0"
            }`}
          />
        </button>
      </div>

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

export default BankLoanApplyForm;
