"use client";

import React, { useState, useEffect } from "react";
import Image from "next/image";
import Link from "next/link";
import { BadgePercent } from "lucide-react";
import type { CalculatorConfig } from "@/types/home";
import type { OrderServiceConfig, PricingConfig } from "@/services/joomlaService";
import calculatorConstants from "@/data/calculator-constants.json";
import serviceJson from "@/data/service-json.json";
import { ExploreFreeToolsBlock } from "@/components/common/ExploreFreeToolsBlock";

interface BlogSidebarProps {
  calculatorConfig: CalculatorConfig;
  orderConfig: OrderServiceConfig[];
  pricing: PricingConfig | null;
}

const SERVICE_OPTIONS = Object.keys(serviceJson.service[0] as Record<string, unknown>);

export const BlogSidebar: React.FC<BlogSidebarProps> = ({
  calculatorConfig,
  orderConfig: _orderConfig,
  pricing,
}) => {
  const [selectedService, setSelectedService] = useState("Essay");

  // Dynamic price calculation
  const rate = pricing?.currencyRates.find(
    (row) => row.country === (calculatorConfig.priceCountry || "IN")
  );
  const conversion = rate?.value ?? 36.14; // Currency multiplier
  const currency = rate?.currency ?? "INR";
  const usdBase = Number(calculatorConstants.currency["1"].price || 13.99);
  const selectedPrice = rate ? usdBase / rate.value : usdBase;
  const staticPrice = pricing?.staticPrice ?? 18.5;

  // 1-page base price after discount
  const baseDiscountedUsd = staticPrice / (100 / (100 - (pricing?.discountPercent ?? 50)));
  const pagePriceInCurrency = rate
    ? (staticPrice / selectedPrice)
    : 668.68;
  const displayPrice = (pagePriceInCurrency > 1000 ? pagePriceInCurrency / conversion : pagePriceInCurrency).toFixed(2);


  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    const targetUrl = calculatorConfig.orderCtaUrl || "/order";
    const serviceParam = encodeURIComponent(selectedService);
    window.location.href = `${targetUrl}?service=${serviceParam}`;
  };

  return (
    <aside className="w-full space-y-6 lg:sticky lg:top-[85px]">
      {/* Block 1: Sidebar Price Quote Form */}
      <div className="bg-white rounded-xl border border-slate-200 shadow-md p-5 text-left">
        {/* Header with Icon, Price & Subtitle */}
        <div className="flex items-start gap-3 mb-4">
          <div className="w-10 h-10 rounded-full bg-green-50 border border-green-200 flex items-center justify-center shrink-0 text-[#5c8032] mt-0.5">
            <BadgePercent className="w-6 h-6" />
          </div>
          <div>
            <h3 className="text-lg sm:text-xl font-bold text-slate-800 leading-tight">
              Lowest price <span className="text-[#e60000] font-extrabold">{currency} {displayPrice}</span>
            </h3>
            <p className="text-xs sm:text-sm font-medium text-slate-500 mt-0.5">
              Get A+ Within Your Budget!
            </p>
          </div>
        </div>

        {/* Service Form */}
        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label htmlFor="blog_sidebar_service" className="sr-only">
              Select Service
            </label>
            <div className="relative">
              <select
                id="blog_sidebar_service"
                value={selectedService}
                onChange={(e) => setSelectedService(e.target.value)}
                className="w-full appearance-none bg-white border border-slate-300 rounded-lg py-3 px-3.5 pr-10 text-sm font-medium text-slate-700 focus:outline-none focus:ring-2 focus:ring-[#5c8032] focus:border-transparent cursor-pointer shadow-xs"
              >
                {SERVICE_OPTIONS.map((srv) => (
                  <option key={srv} value={srv}>
                    {srv}
                  </option>
                ))}
              </select>
              <div className="pointer-events-none absolute inset-y-0 right-0 flex items-center px-3 text-slate-500">
                <svg className="w-4 h-4 fill-current" viewBox="0 0 20 20">
                  <path d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" />
                </svg>
              </div>
            </div>
          </div>

          <button
            type="submit"
            className="w-full bg-[#5c8032] hover:bg-[#4c6b29] active:bg-[#415b22] text-white font-bold text-base py-3 px-4 rounded-lg shadow-sm transition-colors duration-150 flex items-center justify-center cursor-pointer"
          >
            Get Price Quote
          </button>
        </form>
      </div>

      {/* Block 2: Explore Our FREE Tools */}
      <ExploreFreeToolsBlock />

      {/* Block 3: Big Project Or Small Hurdle? Banner */}
      <div
        className="rounded-2xl p-5 relative overflow-hidden text-white shadow-md flex items-center justify-between min-h-[190px]"
        style={{
          background: "linear-gradient(135deg, #5c8032 0%, #466324 100%)",
        }}
      >
        {/* Decorative light burst circles in background */}
        <div
          className="absolute -right-10 -bottom-10 w-44 h-44 rounded-full opacity-20 pointer-events-none"
          style={{ background: "radial-gradient(circle, #ffffff 0%, transparent 70%)" }}
        />

        {/* Left Content */}
        <div className="relative z-10 max-w-[62%] space-y-2 text-left">
          <h3 className="text-lg sm:text-xl font-bold leading-snug text-white">
            Big Project <span className="font-normal">Or</span> Small Hurdle?
          </h3>
          <p className="text-xs sm:text-sm text-white/95 leading-relaxed font-normal">
            Our Exciting Offers are For Every Student.
          </p>

          <a
            href={calculatorConfig.orderCtaUrl || "/offers"}
            className="inline-block mt-3 bg-[#f58e0e] hover:bg-[#e07d00] text-white font-bold text-sm px-5 py-2.5 rounded-lg shadow-sm transition-colors"
          >
            Explore offers!
          </a>
        </div>

        {/* Right Graphic / Student Image */}
        <div className="relative z-10 shrink-0 w-[35%] h-[160px] -mr-2 -mb-5">
          <Image
            src="/images/whatsapp-phone-girl.png"
            alt="Student Exciting Offers"
            fill
            sizes="140px"
            className="object-contain object-bottom drop-shadow-md"
          />
        </div>
      </div>
    </aside>
  );


};
