"use client";

import { useState, useEffect } from "react";
import { FaUser, FaEnvelope, FaPhoneAlt, FaRupeeSign, FaHandHoldingHeart, FaPaperPlane, FaLock } from "react-icons/fa";

const amounts = [501, 1100, 2100, 5100, 11000];

export default function DonationForm() {
  const [loading, setLoading] = useState(false);
  const [formData, setFormData] = useState({ name: "", email: "", phone: "", amount: "", purpose: "General Donation", message: "" });

  useEffect(() => {
    const script = document.createElement("script");
    script.src = "https://checkout.razorpay.com/v1/checkout.js";
    script.async = true;
    document.body.appendChild(script);
  }, []);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    setFormData((prev) => ({ ...prev, [e.target.name]: e.target.value }));
  };

  const handlePayment = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setLoading(true);
    try {
      const orderRes = await fetch("/api/razorpay/create-order", {
        method: "POST",
        body: JSON.stringify({ amount: formData.amount }),
      });
      const { orderId } = await orderRes.json();

      const options = {
        key: process.env.NEXT_PUBLIC_RAZORPAY_KEY_ID,
        amount: Number(formData.amount) * 100,
        currency: "INR",
        name: "Rajvi Social Welfare Trust",
        description: formData.purpose,
        order_id: orderId,
        theme: { color: "#f59e0b" }, // Premium Amber theme
        handler: async function (response: any) {
          await fetch("/api/donation", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ ...formData, paymentId: response.razorpay_payment_id }),
          });
          alert("Donation Successful! Thank you for your kindness.");
          setFormData({ name: "", email: "", phone: "", amount: "", purpose: "General Donation", message: "" });
        },
      };

      const paymentObject = new (window as any).Razorpay(options);
      paymentObject.open();
    } catch (error) {
      alert("Payment failed. Please try again.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <section className="relative overflow-hidden rounded-[2rem] bg-white p-6 shadow-[0_20px_50px_rgba(0,0,0,0.05)] sm:p-10 border border-slate-100">
      <div className="mb-8 text-center">
        <h2 className="text-3xl font-black text-slate-950">Make a Difference</h2>
        <p className="mt-2 text-slate-500">Your contribution brings hope to many lives.</p>
      </div>

      <form onSubmit={handlePayment} className="grid gap-6">
        {/* Input Fields with Floating Labels Look */}
        <div className="grid md:grid-cols-2 gap-6">
          {[
            { name: "name", icon: FaUser, placeholder: "Full Name" },
            { name: "email", icon: FaEnvelope, placeholder: "Email Address" },
          ].map((field) => (
            <div key={field.name} className="relative group">
              <field.icon className="absolute left-4 top-4 text-amber-500 transition-colors group-focus-within:text-amber-600" />
              <input name={field.name} value={formData[field.name as keyof typeof formData]} onChange={handleChange} required placeholder={field.placeholder} className="h-14 w-full rounded-2xl border border-slate-200 pl-12 pr-4 outline-none transition-all focus:border-amber-500 focus:ring-4 focus:ring-amber-500/10 hover:border-amber-300" />
            </div>
          ))}
        </div>

        {/* Amount Selector */}
        <div>
          <label className="mb-3 block text-sm font-bold text-slate-700">Select Amount (₹)</label>
          <div className="grid grid-cols-3 sm:grid-cols-5 gap-3">
            {amounts.map((amt) => (
              <button key={amt} type="button" onClick={() => setFormData(p => ({ ...p, amount: String(amt) }))} 
                className={`py-3 rounded-xl border font-bold transition-all ${formData.amount === String(amt) ? "bg-amber-500 text-white border-amber-500 shadow-lg shadow-amber-500/20" : "bg-slate-50 border-slate-200 hover:border-amber-400"}`}>
                ₹{amt}
              </button>
            ))}
          </div>
        </div>

        {/* Custom Amount */}
        <div className="relative group">
          <FaRupeeSign className="absolute left-4 top-4 text-amber-500" />
          <input type="number" name="amount" value={formData.amount} onChange={handleChange} required placeholder="Enter custom amount" className="h-14 w-full rounded-2xl border border-slate-200 pl-12 pr-4 outline-none transition-all focus:border-amber-500 focus:ring-4 focus:ring-amber-500/10" />
        </div>

        {/* Submit Button */}
        <button type="submit" disabled={loading} className="w-full h-14 bg-slate-950 text-white rounded-2xl font-bold flex items-center justify-center gap-2 hover:bg-slate-800 transition-all active:scale-[0.98] disabled:opacity-50">
          {loading ? "Processing..." : (
            <>
              <FaLock className="text-xs opacity-70" />
              Secure Pay ₹{formData.amount || "0"}
              <FaPaperPlane className="text-xs" />
            </>
          )}
        </button>
      </form>
    </section>
  );
}