"use client";
import {useState} from "react";
import {sendEmail} from "@/app/actions/sendEmail";

const WarrantySection = () => {
  const [fileName, setFileName] = useState("No file chosen");
  const [formState, setFormState] = useState({
    loading: false,
    error: null,
    success: false,
  });

  const handleFileChange = (e) => {
    const file = e.target.files[0];
    if (!file) {
      setFileName("No file chosen");
      return;
    }

    // Validate file type and size
    const validTypes = ["image/jpeg", "image/png"];
    const maxSize = 5 * 1024 * 1024; // 5MB

    if (!validTypes.includes(file.type)) {
      setFormState({...formState, error: "Only JPG/PNG files are allowed"});
      e.target.value = ""; // Clear invalid file
      setFileName("Invalid file type");
      return;
    }

    if (file.size > maxSize) {
      setFormState({...formState, error: "File size exceeds 5MB limit"});
      e.target.value = ""; // Clear invalid file
      setFileName("File too large");
      return;
    }

    setFileName(file.name);
    setFormState({...formState, error: null});
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setFormState({loading: true, error: null, success: false});

    const formData = new FormData(e.target);

    try {
      const result = await sendEmail(formData);
      if (result.error) throw new Error(result.error);

      setFormState({loading: false, error: null, success: true});
      e.target.reset();
      setFileName("No file chosen");
    } catch (error) {
      setFormState({loading: false, error: error.message, success: false});
    }
  };

  return (
    <section className="mb-10 w-full">
      <div className="mx-auto max-w-screen-2xl px-5 py-10 sm:px-8 lg:px-10 lg:py-16">
        <div className="grid grid-cols-1 gap-10 lg:grid-cols-2 xl:gap-20">
          <div className="flex flex-col gap-6">
            <h1 className="flex flex-row items-center gap-2">Warranty Care</h1>
            <p>Enjoy peace of mind with Verola®'s reliable warranty care. We’re committed to ensuring your satisfaction by offering comprehensive support for any product issues. Let us take care of your seating needs so you can focus on what matters most.</p>
            <div className="flex flex-col gap-6">
              {[
                {
                  title: "Comprehensive Coverage",
                  description: "Verola® warranty covers manufacturing defects and ensures your office furniture meets the highest quality standards.",
                },
                {
                  title: "Hassle-Free Claims",
                  description: "Enjoy an easy and transparent process for warranty claims, with quick resolutions to keep you stress-free.",
                },
                {
                  title: "Dedicated Support",
                  description: "Our professional support team is always ready to assist you with any questions or issues regarding your warranty.",
                },
              ].map((item, index) => (
                <div key={index} className="flex flex-row items-start gap-2">
                  <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth="2" stroke="currentColor" className="size-6 shrink-0 text-vgreen">
                    <path strokeLinecap="round" strokeLinejoin="round" d="M9 12.75 11.25 15 15 9.75M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z" />
                  </svg>
                  <div className="flex flex-col gap-1">
                    <p className="font-semibold text-vgreen">{item.title}</p>
                    <p className="text-sm">{item.description}</p>
                  </div>
                </div>
              ))}
            </div>
          </div>

          <div className="flex flex-col gap-6">
            <form className="flex flex-col gap-6 rounded-2xl border border-slate-300 p-5 text-sm sm:p-10 lg:grow" onSubmit={handleSubmit}>
              {/* Form fields */}
              <div className="flex flex-col gap-6 lg:grow">
                {/* Service selection */}
                <div className="flex flex-col gap-2">
                  <label className="text-xs font-medium" htmlFor="services">
                    Select Services*
                  </label>
                  <select name="warranty_services" id="services" required className="appearance-none rounded-lg border-0 bg-transparent bg-select bg-contain bg-[right] bg-no-repeat px-3 py-2 outline-none ring-1 ring-inset ring-slate-300 placeholder:text-slate-400 focus:ring-2 focus:ring-inset focus:ring-vgreen">
                    <option value="Warranty Claims">Warranty Claims</option>
                    <option value="Order Spare Parts">Order Spare Parts</option>
                  </select>
                </div>

                {/* Product selection */}
                <div className="flex flex-col gap-2">
                  <label className="text-xs font-medium" htmlFor="products">
                    Select Products*
                  </label>
                  <select name="warranty_products" id="products" required className="appearance-none rounded-lg border-0 bg-transparent bg-select bg-contain bg-[right] bg-no-repeat px-3 py-2 outline-none ring-1 ring-inset ring-slate-300 placeholder:text-slate-400 focus:ring-2 focus:ring-inset focus:ring-vgreen">
                    {["S3", "S2", "K2", "K5", "ST8", "ST8F", "T8", "X6", "F1", "F2", "F3"].map((product) => (
                      <option key={product} value={product}>
                        {product}
                      </option>
                    ))}
                  </select>
                </div>

                {/* File upload section */}
                <div className="flex flex-col gap-2">
                  <p className="text-xs font-medium">Upload photo of the damaged part (JPG/PNG, max 5MB)</p>
                  <div className="flex flex-row items-center gap-2">
                    <input type="file" id="upload" name="attachment" hidden onChange={handleFileChange} accept=".jpg,.jpeg,.png" />
                    <label htmlFor="upload" className="flex w-fit cursor-pointer flex-row items-center gap-2 rounded-lg border border-slate-300 px-3 py-2">
                      <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth="2" stroke="currentColor" className="size-4 shrink-0">
                        <path strokeLinecap="round" strokeLinejoin="round" d="M3 16.5v2.25A2.25 2.25 0 0 0 5.25 21h13.5A2.25 2.25 0 0 0 21 18.75V16.5m-13.5-9L12 3m0 0 4.5 4.5M12 3v13.5" />
                      </svg>
                      <span>Choose File</span>
                    </label>
                    <span className="text-sm">{fileName}</span>
                  </div>
                </div>

                {/* Contact info */}
                <div className="grid grid-cols-1 gap-6 sm:grid-cols-2">
                  <div className="flex flex-col gap-2 sm:col-span-2">
                    <label className="text-xs font-medium" htmlFor="name">
                      Name*
                    </label>
                    <input type="text" name="warranty_name" id="name" placeholder="Jane Smith" required className="appearance-none rounded-lg border-0 px-3 py-2 outline-none ring-1 ring-inset ring-slate-300 placeholder:text-slate-400 focus:ring-2 focus:ring-inset focus:ring-vgreen" />
                  </div>
                  <div className="flex flex-col gap-2">
                    <label className="text-xs font-medium" htmlFor="email">
                      Email*
                    </label>
                    <input type="email" name="warranty_email" id="email" placeholder="you@example.com" required className="appearance-none rounded-lg border-0 px-3 py-2 outline-none ring-1 ring-inset ring-slate-300 placeholder:text-slate-400 focus:ring-2 focus:ring-inset focus:ring-vgreen" />
                  </div>
                  <div className="flex flex-col gap-2">
                    <label className="text-xs font-medium" htmlFor="phone">
                      Phone Number*
                    </label>
                    <input type="tel" name="warranty_phone" id="phone" placeholder="+62 8123456789" required className="appearance-none rounded-lg border-0 px-3 py-2 outline-none ring-1 ring-inset ring-slate-300 placeholder:text-slate-400 focus:ring-2 focus:ring-inset focus:ring-vgreen" />
                  </div>
                </div>
              </div>

              {/* Status messages */}
              {formState.error && <p className="text-red-500 text-sm">{formState.error}</p>}
              {formState.success && <p className="text-green-500 text-sm">Your warranty request has been submitted successfully!</p>}

              {/* Submit button */}
              <div className="flex justify-end py-2">
                <button type="submit" disabled={formState.loading} className="group flex h-10 w-fit flex-row items-center gap-2 rounded-lg bg-green-500 px-4 text-sm font-medium text-white transition duration-150 ease-in-out disabled:opacity-50">
                  {formState.loading ? (
                    "Submitting..."
                  ) : (
                    <>
                      <span>Submit</span>
                      <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth="2" stroke="currentColor" className="size-5 transition duration-300 ease-in-out group-hover:translate-x-1">
                        <path strokeLinecap="round" strokeLinejoin="round" d="M17.25 8.25 21 12m0 0-3.75 3.75M21 12H3" />
                      </svg>
                    </>
                  )}
                </button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </section>
  );
};

export default WarrantySection;
