"use client";

import React, { useState, useEffect } from "react";

interface ServiceOption {
  groupId: number;
  label: string;
  unit?: string;
  options?: Array<{ id: number; name: string }>;
}

interface SubjectOption {
  value: string;
  label: string;
  group?: string;
  addonPrice?: number;
}

interface UrgencyOption {
  value: string;
  label: string;
}

interface PricingCalculatorProps {
  orderCtaUrl: string;
  currency: string;
  initialCustomPrice: number;
  initialEstimatedPrice: number;
  discountPercent: number;
  rateValue?: number;
}

export function PricingCalculator({
  orderCtaUrl,
  currency,
  initialCustomPrice,
  initialEstimatedPrice,
  discountPercent,
  rateValue = 1,
}: PricingCalculatorProps) {
  const [services, setServices] = useState<ServiceOption[]>([]);
  const [service, setService] = useState<string>("");
  const [subjects, setSubjects] = useState<SubjectOption[]>([]);
  const [subjectId, setSubjectId] = useState<string>("");
  const [pages, setPages] = useState<number>(1);
  const [urgency, setUrgency] = useState<string>("");
  const [urgencyOptions, setUrgencyOptions] = useState<UrgencyOption[]>([]);

  const [currentBasePrice, setCurrentBasePrice] = useState<number>(initialEstimatedPrice);
  const [currentOfferPrice, setCurrentOfferPrice] = useState<number>(initialCustomPrice);

  // Fetch available services
  useEffect(() => {
    fetch("/api/services")
      .then((res) => (res.ok ? res.json() : null))
      .then((data) => {
        if (data?.services && Array.isArray(data.services) && data.services.length > 0) {
          setServices(data.services);
        }
      })
      .catch(() => {});
  }, []);

  const selectedService = services.find((s) => s.label === service);

  // Fetch subjects when service changes
  useEffect(() => {
    setSubjectId("");
    if (!selectedService) {
      setSubjects([]);
      return;
    }
    const controller = new AbortController();
    fetch("/api/subjects", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        groupId: selectedService.groupId,
        unitTag: selectedService.unit || "Pages | Words",
        serviceName: selectedService.label,
      }),
      signal: controller.signal,
    })
      .then((res) => (res.ok ? res.json() : null))
      .then((data) => setSubjects(data?.subjects ?? []))
      .catch(() => setSubjects([]));
    return () => controller.abort();
  }, [selectedService]);

  // Fetch urgency options when service changes
  useEffect(() => {
    setUrgency("");
    if (!selectedService) {
      setUrgencyOptions([]);
      return;
    }
    const controller = new AbortController();
    fetch("/api/urgency", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ assignmentId: selectedService.groupId }),
      signal: controller.signal,
    })
      .then((res) => (res.ok ? res.json() : null))
      .then((data) => {
        if (data?.urgencies && Array.isArray(data.urgencies)) {
          setUrgencyOptions(data.urgencies);
        }
      })
      .catch(() => setUrgencyOptions([]));
    return () => controller.abort();
  }, [selectedService]);

  const selectedSubject = subjects.find((s) => s.value === subjectId);

  // Price quote calculation
  useEffect(() => {
    if (!service || !urgency) {
      setCurrentBasePrice(initialEstimatedPrice * pages);
      setCurrentOfferPrice(initialCustomPrice * pages);
      return;
    }

    const controller = new AbortController();
    fetch("/api/price", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        assignmentId: selectedService?.groupId,
        page: pages,
        urgency,
        serviceGroupId: selectedService?.groupId,
        serviceName: selectedService?.label,
        addonPrice: selectedSubject?.addonPrice,
      }),
      signal: controller.signal,
    })
      .then((res) => (res.ok ? res.json() : null))
      .then((data) => {
        if (data && !data.error && typeof data.totalPrice === "number") {
          const mult = rateValue > 0 ? rateValue : 1;
          const discounted = Math.round(data.totalPrice * mult * 100) / 100;
          const beforeDiscount = Math.round(data.totalPriceBeforeDiscount * mult * 100) / 100;
          setCurrentOfferPrice(discounted);
          setCurrentBasePrice(beforeDiscount);
        } else {
          setCurrentBasePrice(initialEstimatedPrice * pages);
          setCurrentOfferPrice(initialCustomPrice * pages);
        }
      })
      .catch(() => {
        setCurrentBasePrice(initialEstimatedPrice * pages);
        setCurrentOfferPrice(initialCustomPrice * pages);
      });

    return () => controller.abort();
  }, [service, subjectId, pages, urgency, selectedService, selectedSubject, rateValue, initialCustomPrice, initialEstimatedPrice]);

  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const targetUrl = new URL(orderCtaUrl, window.location.href);
    if (selectedService?.label) targetUrl.searchParams.set("service", selectedService.label);
    if (subjectId) targetUrl.searchParams.set("subject", subjectId);
    if (pages) targetUrl.searchParams.set("pages", String(pages));
    if (urgency) targetUrl.searchParams.set("urgency", urgency);
    window.location.href = targetUrl.toString();
  };

  return (
    <form method="post" onSubmit={handleSubmit} id="bannerform">
      <p className="head">Calculate your price</p>
      <div className="pricing-form-box">
        <div className="loader">
          <div className="pricebx">
            <label
              style={{ left: "-9999em", opacity: 0, position: "absolute" }}
              htmlFor="ass_group_list"
              className="hidden-label"
            >
              Select Services
            </label>
            <select
              id="ass_group_list"
              aria-label="assignment"
              name="group_id"
              value={service}
              onChange={(e) => setService(e.target.value)}
            >
              <option value="">Select Services</option>
              {services.map((s, idx) => (
                <option key={idx} value={s.label}>
                  {s.label}
                </option>
              ))}
            </select>
            <div className="hd">
              <input type="hidden" value={selectedService?.groupId || ""} name="doctype_id" className="assignment" id="assignment" />
              <input type="hidden" value="" name="group_unit_hidden" id="group_unit_hidden" className="group_unit_hidden" />
              <input type="hidden" value={selectedService?.label || ""} name="assignment_service" className="assignment_service" id="assignment_service" />
            </div>
          </div>

          <div className="pricebx" id="get_subject">
            <select
              name="subjectId"
              id="assignment_subject"
              aria-label="subject"
              value={subjectId}
              onChange={(e) => setSubjectId(e.target.value)}
            >
              <option value="">Select Subject</option>
              {subjects.map((sub, idx) => (
                <option key={idx} value={sub.value}>
                  {sub.label}
                </option>
              ))}
            </select>
          </div>

          <div className="pricebx" id="pages_count_parent">
            <select
              id="pages_count"
              name="pages"
              aria-label="pages"
              value={pages}
              onChange={(e) => setPages(Number(e.target.value) || 1)}
            >
              <option value="">Select Pages</option>
              {Array.from({ length: 50 }, (_, i) => i + 1).map((p) => (
                <option key={p} value={p}>
                  {p} {p === 1 ? "Page" : "Pages"} / {p * 250} Words
                </option>
              ))}
            </select>
          </div>

          <div className="pricebx">
            <select
              id="urgency"
              name="urgency"
              aria-label="urgency"
              value={urgency}
              onChange={(e) => setUrgency(e.target.value)}
            >
              <option value="">Select Urgency</option>
              {urgencyOptions.length > 0 ? (
                urgencyOptions.map((u, idx) => (
                  <option key={idx} value={u.value}>
                    {u.label}
                  </option>
                ))
              ) : (
                <>
                  <option value="15">15+ Days</option>
                  <option value="10">10 Days</option>
                  <option value="7">7 Days</option>
                  <option value="6">6 Days</option>
                  <option value="5">5 Days</option>
                  <option value="4">4 Days</option>
                  <option value="3">3 Days</option>
                  <option value="2">48 Hours</option>
                  <option value="1">24 Hours</option>
                </>
              )}
            </select>
          </div>

          <div className="Estimate-price">
            <label>Estimated Price</label>{" "}
            <span className="basePrice">
              {currency} {currentBasePrice.toFixed(2)}
            </span>{" "}
            <span className="priceoff">{discountPercent}% OFF</span>
            <p className="symbole">
              {currency} <span className="value offerPrice">{currentOfferPrice.toFixed(2)}</span>
            </p>
          </div>
        </div>

        <button type="submit" className="btn-ordernow">
          ORDER NOW
        </button>
      </div>
    </form>
  );
}
