"use client";

import React, { useState } from "react";
import { useCart } from "@/context/CartContext";
import {
  X,
  FileText,
  Building2,
  GraduationCap,
  Send,
  CheckCircle2,
  Phone,
  Mail,
} from "lucide-react";

export const BulkQuoteModal: React.FC = () => {
  const { isQuoteModalOpen, setIsQuoteModalOpen } = useCart();

  const [orgType, setOrgType] = useState("School / Academy");
  const [orgName, setOrgName] = useState("");
  const [contactPerson, setContactPerson] = useState("");
  const [email, setEmail] = useState("");
  const [phone, setPhone] = useState("");
  const [province, setProvince] = useState("Gauteng");
  const [requirements, setRequirements] = useState("");

  const [isSubmitting, setIsSubmitting] = useState(false);
  const [submitted, setSubmitted] = useState(false);

  if (!isQuoteModalOpen) return null;

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!orgName || !contactPerson || !email || !requirements) return;

    setIsSubmitting(true);
    try {
      const res = await fetch("/api/quotes", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          organizationType: orgType,
          organizationName: orgName,
          contactPerson,
          email,
          phone,
          province,
          requirementsText: requirements,
        }),
      });

      const data = await res.json();
      if (data.success) {
        setSubmitted(true);
      } else {
        alert(data.error || "Submission failed");
      }
    } catch (err) {
      console.error(err);
      alert("Error submitting quote request");
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="fixed inset-0 z-50 overflow-y-auto bg-slate-950/70 backdrop-blur-sm flex items-center justify-center p-3 sm:p-6 animate-fadeIn">
      <div className="relative bg-white rounded-3xl shadow-2xl border border-slate-200 w-full max-w-2xl overflow-hidden my-auto p-5 sm:p-8">
        {/* Close Button */}
        <button
          onClick={() => {
            setIsQuoteModalOpen(false);
            setSubmitted(false);
          }}
          className="absolute top-4 right-4 z-20 bg-slate-100 hover:bg-slate-200 text-slate-700 p-2 rounded-full transition-colors"
        >
          <X className="w-5 h-5" />
        </button>

        {!submitted ? (
          <div>
            <div className="flex items-center gap-3 pb-4 mb-5 border-b border-slate-200">
              <div className="w-10 h-10 rounded-xl bg-amber-500/20 text-amber-700 flex items-center justify-center">
                <FileText className="w-5 h-5" />
              </div>
              <div>
                <h2 className="font-extrabold text-xl text-slate-900">Request School & Office Bulk Quote</h2>
                <p className="text-xs text-slate-500">Get custom discounted pricing on high-volume stationery orders</p>
              </div>
            </div>

            <form onSubmit={handleSubmit} className="space-y-4">
              <div className="grid sm:grid-cols-2 gap-3">
                <div>
                  <label className="block text-[11px] font-bold text-slate-600 mb-1">Organization Type *</label>
                  <select
                    value={orgType}
                    onChange={(e) => setOrgType(e.target.value)}
                    className="w-full px-3 py-2 text-xs bg-slate-50 border border-slate-300 rounded-xl"
                  >
                    <option value="School / Academy">School / Academy</option>
                    <option value="Corporate / Company">Corporate / Company</option>
                    <option value="Non-Profit Organization">Non-Profit Organization</option>
                    <option value="Government Dept">Government Department</option>
                    <option value="Individual Bulk Order">Individual Bulk Order</option>
                  </select>
                </div>

                <div>
                  <label className="block text-[11px] font-bold text-slate-600 mb-1">School or Company Name *</label>
                  <input
                    type="text"
                    placeholder="e.g. St Johns High / Absa Branch"
                    value={orgName}
                    onChange={(e) => setOrgName(e.target.value)}
                    required
                    className="w-full px-3 py-2 text-xs bg-slate-50 border border-slate-300 rounded-xl"
                  />
                </div>
              </div>

              <div className="grid sm:grid-cols-2 gap-3">
                <div>
                  <label className="block text-[11px] font-bold text-slate-600 mb-1">Contact Person Name *</label>
                  <input
                    type="text"
                    placeholder="e.g. Mrs S. Naidoo"
                    value={contactPerson}
                    onChange={(e) => setContactPerson(e.target.value)}
                    required
                    className="w-full px-3 py-2 text-xs bg-slate-50 border border-slate-300 rounded-xl"
                  />
                </div>

                <div>
                  <label className="block text-[11px] font-bold text-slate-600 mb-1">Email Address *</label>
                  <input
                    type="email"
                    placeholder="e.g. admin@school.co.za"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    required
                    className="w-full px-3 py-2 text-xs bg-slate-50 border border-slate-300 rounded-xl"
                  />
                </div>
              </div>

              <div className="grid sm:grid-cols-2 gap-3">
                <div>
                  <label className="block text-[11px] font-bold text-slate-600 mb-1">Contact Phone / Cell *</label>
                  <input
                    type="tel"
                    placeholder="e.g. 011 987 6543"
                    value={phone}
                    onChange={(e) => setPhone(e.target.value)}
                    required
                    className="w-full px-3 py-2 text-xs bg-slate-50 border border-slate-300 rounded-xl"
                  />
                </div>

                <div>
                  <label className="block text-[11px] font-bold text-slate-600 mb-1">Province *</label>
                  <select
                    value={province}
                    onChange={(e) => setProvince(e.target.value)}
                    className="w-full px-3 py-2 text-xs bg-slate-50 border border-slate-300 rounded-xl"
                  >
                    <option value="Gauteng">Gauteng</option>
                    <option value="Western Cape">Western Cape</option>
                    <option value="KwaZulu-Natal">KwaZulu-Natal</option>
                    <option value="Eastern Cape">Eastern Cape</option>
                    <option value="Free State">Free State</option>
                    <option value="Limpopo">Limpopo</option>
                    <option value="Mpumalanga">Mpumalanga</option>
                    <option value="North West">North West</option>
                    <option value="Northern Cape">Northern Cape</option>
                  </select>
                </div>
              </div>

              <div>
                <label className="block text-[11px] font-bold text-slate-600 mb-1">Stationery List / Requirement Details *</label>
                <textarea
                  placeholder="Paste your school supply list or required quantities (e.g., 50x Typek A4 boxes, 200x BIC Black pens, 100x Casio FX-82ZA calculators)..."
                  value={requirements}
                  onChange={(e) => setRequirements(e.target.value)}
                  required
                  rows={4}
                  className="w-full px-3 py-2 text-xs bg-slate-50 border border-slate-300 rounded-xl focus:bg-white focus:ring-1 focus:ring-blue-900"
                />
              </div>

              <button
                type="submit"
                disabled={isSubmitting}
                className="w-full py-3 bg-gradient-to-r from-amber-500 to-amber-600 hover:from-amber-600 hover:to-amber-700 text-slate-950 font-extrabold text-xs rounded-xl shadow-md transition-colors flex items-center justify-center gap-2 cursor-pointer"
              >
                <Send className="w-4 h-4" />
                <span>{isSubmitting ? "Submitting..." : "SUBMIT FOR FORMAL INVOICE QUOTE"}</span>
              </button>
            </form>
          </div>
        ) : (
          <div className="py-8 px-4 text-center space-y-4">
            <div className="w-16 h-16 rounded-full bg-emerald-100 text-emerald-600 flex items-center justify-center mx-auto">
              <CheckCircle2 className="w-8 h-8" />
            </div>
            <h3 className="text-xl font-extrabold text-slate-900">Quote Request Received!</h3>
            <p className="text-xs text-slate-600 max-w-md mx-auto">
              Our dedicated sales team will process your stationery requirements and email an official Tax Invoice quote to <strong className="text-slate-900">{email}</strong> within 2 business hours.
            </p>
            <button
              onClick={() => {
                setIsQuoteModalOpen(false);
                setSubmitted(false);
              }}
              className="px-6 py-2.5 bg-blue-950 text-white font-bold text-xs rounded-xl hover:bg-slate-900 transition-colors"
            >
              Done
            </button>
          </div>
        )}
      </div>
    </div>
  );
};
