"use client";

import { useState } from "react";
import Link from "next/link";
import {
  MapPin, Building2, Clock, Tag, ChevronDown, ChevronUp,
  IndianRupee, Info, BadgePercent, CheckCircle2,
} from "lucide-react";
import type { CityPriceBreakdown, CarDiscounts, WaitingPeriod } from "@/lib/types";
import { cn } from "@/lib/utils";

// ── helpers ───────────────────────────────────────────────────────────────────

function fmtINR(n: number | undefined): string {
  if (!n) return "—";
  if (n >= 10_000_000) return `₹${(n / 10_000_000).toFixed(2)} Cr`;
  if (n >= 100_000)    return `₹${(n / 100_000).toFixed(2)} L`;
  return `₹${n.toLocaleString("en-IN")}`;
}

function WaitBadge({ weeks }: { weeks: { min: number; max: number } | null | undefined }) {
  if (!weeks) return null;
  const { min, max } = weeks;
  const color =
    max <= 4  ? "bg-green-50 text-green-700 border-green-200" :
    max <= 12 ? "bg-amber-50 text-amber-700 border-amber-200" :
                "bg-red-50   text-red-700   border-red-200";
  return (
    <div className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-xl border text-xs font-bold ${color}`}>
      <Clock className="w-3 h-3" />
      {min === max ? `${min}w` : `${min}–${max}w`} wait
    </div>
  );
}

// ── Offer chip ────────────────────────────────────────────────────────────────

const OFFER_COLOR: Record<string, string> = {
  cash:       "bg-green-50  text-green-700  border-green-200",
  exchange:   "bg-blue-50   text-blue-700   border-blue-200",
  bank:       "bg-purple-50 text-purple-700 border-purple-200",
  corporate:  "bg-teal-50   text-teal-700   border-teal-200",
  loyalty:    "bg-amber-50  text-amber-700  border-amber-200",
  festive:    "bg-rose-50   text-rose-700   border-rose-200",
  other:      "bg-gray-50   text-gray-700   border-gray-200",
};
const OFFER_LABEL: Record<string, string> = {
  cash: "Cash", exchange: "Exchange", bank: "Bank",
  corporate: "Corporate", loyalty: "Loyalty", festive: "Festive", other: "Offer",
};

// ── Main ──────────────────────────────────────────────────────────────────────

interface Props {
  carId:      string;
  carName:    string;
  prices:     CityPriceBreakdown[];
  discounts:  CarDiscounts | null;
  waiting:    WaitingPeriod | null;
}

export default function CityPricingSection({
  carId, carName, prices, discounts, waiting,
}: Props) {
  const [expandedCity, setExpandedCity] = useState<string | null>(null);
  const [showAllCities, setShowAllCities] = useState(false);
  const [showAllOffers, setShowAllOffers] = useState(false);

  if (prices.length === 0 && !discounts && !waiting) return null;

  const displayPrices = showAllCities ? prices : prices.slice(0, 8);
  const hasOffers     = (discounts?.offerCount ?? 0) > 0;
  const displayOffers = showAllOffers
    ? (discounts?.offers ?? [])
    : (discounts?.offers ?? []).slice(0, 4);

  return (
    <div className="rounded-[32px] bg-white border border-gray-200/60 p-6 md:p-8 shadow-[0_10px_40px_rgba(0,0,0,0.05)] mb-6">

      {/* ── Header ── */}
      <div className="flex items-start justify-between gap-4 mb-6">
        <div className="flex items-center gap-4">
          <div className="w-12 h-12 rounded-2xl bg-blue-50 flex items-center justify-center shrink-0">
            <MapPin className="w-6 h-6 text-blue-500" />
          </div>
          <div>
            <p className="text-[10px] uppercase tracking-[0.2em] text-blue-500 font-black">City Wise</p>
            <h2 className="text-xl font-black text-gray-900">On-Road Prices</h2>
            <p className="text-xs text-gray-400 mt-0.5">
              Ex-showroom + RTO + Insurance + TCS
            </p>
          </div>
        </div>

        {/* Total savings badge */}
        {hasOffers && (
          <div className="shrink-0 rounded-2xl bg-green-50 border border-green-200 px-4 py-2 text-center">
            <p className="text-[10px] uppercase tracking-wider text-green-600 font-black">Save up to</p>
            <p className="text-lg font-black text-green-700">{fmtINR(discounts!.totalDiscount)}</p>
            <p className="text-[10px] text-green-500">{discounts!.offerCount} offers</p>
          </div>
        )}
      </div>

      {/* ── City price table ── */}
      {prices.length > 0 && (
        <div className="mb-6">
          <div className="overflow-x-auto rounded-2xl border border-gray-100">
            <table className="w-full min-w-[560px]">
              <thead className="bg-gradient-to-r from-gray-50 to-blue-50 border-b border-gray-100">
                <tr>
                  {["City", "Ex-showroom", "RTO", "Insurance", "On-Road Price", ""].map((h) => (
                    <th key={h} className={cn(
                      "px-4 py-3 text-[10px] uppercase tracking-wider text-gray-500 font-black",
                      h === "On-Road Price" ? "text-right" : h === "" ? "" : "text-left"
                    )}>
                      {h}
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {displayPrices.map((p) => {
                  const isExpanded = expandedCity === p.city;
                  return [
                    <tr
                      key={p.city}
                      className="border-b border-gray-50 hover:bg-blue-50/30 transition-colors cursor-pointer"
                      onClick={() => setExpandedCity(isExpanded ? null : p.city)}
                    >
                      <td className="px-4 py-4">
                        <div className="flex items-center gap-2">
                          <MapPin className="w-3.5 h-3.5 text-gray-400 shrink-0" />
                          <span className="font-bold text-gray-800 text-sm">{p.city}</span>
                          {p.isEstimate && (
                            <span className="text-[9px] font-bold px-1.5 py-0.5 rounded-lg bg-amber-50 text-amber-600 border border-amber-200">
                              est
                            </span>
                          )}
                        </div>
                        {p.state && <p className="text-[10px] text-gray-400 ml-5">{p.state}</p>}
                      </td>
                      <td className="px-4 py-4 text-sm text-gray-700">{fmtINR(p.exShowroom)}</td>
                      <td className="px-4 py-4 text-sm text-gray-700">{fmtINR(p.rto)}</td>
                      <td className="px-4 py-4 text-sm text-gray-700">{fmtINR(p.insurance)}</td>
                      <td className="px-4 py-4 text-right font-black text-gray-900 text-sm">
                        {fmtINR(p.onRoadPrice)}
                      </td>
                      <td className="px-4 py-4">
                        {isExpanded
                          ? <ChevronUp className="w-4 h-4 text-gray-400" />
                          : <ChevronDown className="w-4 h-4 text-gray-400" />
                        }
                      </td>
                    </tr>,

                    /* Expanded breakdown row */
                    isExpanded && (
                      <tr key={`${p.city}-detail`} className="bg-blue-50/40 border-b border-gray-100">
                        <td colSpan={6} className="px-6 py-4">
                          <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
                            {[
                              { label: "Ex-showroom",  value: p.exShowroom,  color: "blue" },
                              { label: "RTO / Reg.",   value: p.rto,         color: "purple" },
                              { label: "Insurance",    value: p.insurance,   color: "green" },
                              { label: "TCS",          value: p.tcs,         color: "orange" },
                              { label: "FASTag",       value: p.fastag,      color: "teal" },
                              { label: "Handling",     value: p.handling,    color: "gray" },
                            ].filter(r => r.value).map(({ label, value, color }) => (
                              <div key={label} className={`rounded-xl bg-${color}-50 border border-${color}-100 p-3`}>
                                <p className={`text-[10px] font-black uppercase tracking-wide text-${color}-500 mb-1`}>{label}</p>
                                <p className="text-sm font-black text-gray-900">{fmtINR(value)}</p>
                              </div>
                            ))}
                            <div className="rounded-xl bg-gray-900 p-3 col-span-2 flex items-center justify-between">
                              <p className="text-[10px] font-black uppercase tracking-wide text-gray-300">Total On-Road</p>
                              <p className="text-base font-black text-white">{fmtINR(p.onRoadPrice)}</p>
                            </div>
                          </div>
                          {p.isEstimate && (
                            <p className="mt-3 text-[10px] text-amber-600 flex items-center gap-1">
                              <Info className="w-3 h-3" />
                              Estimated price — actual RTO rates may vary. Visit your nearest dealer for exact on-road quote.
                            </p>
                          )}
                        </td>
                      </tr>
                    ),
                  ];
                })}
              </tbody>
            </table>
          </div>

          {prices.length > 8 && (
            <button
              onClick={() => setShowAllCities(!showAllCities)}
              className="mt-3 w-full py-2.5 text-sm font-bold text-blue-600 hover:bg-blue-50 rounded-2xl transition-colors flex items-center justify-center gap-1"
            >
              {showAllCities ? "Show fewer cities" : `Show all ${prices.length} cities`}
              {showAllCities ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" />}
            </button>
          )}
        </div>
      )}

      {/* ── Waiting period ── */}
      {waiting && (waiting.waitingWeeks || waiting.message) && (
        <div className="rounded-2xl border border-amber-200 bg-amber-50 p-4 mb-6 flex items-center gap-4">
          <div className="w-10 h-10 rounded-xl bg-amber-100 flex items-center justify-center shrink-0">
            <Clock className="w-5 h-5 text-amber-600" />
          </div>
          <div>
            <p className="text-xs font-black uppercase tracking-wide text-amber-600">Waiting Period</p>
            {waiting.waitingWeeks ? (
              <p className="text-sm font-bold text-gray-800 mt-0.5">
                {waiting.waitingWeeks.min === waiting.waitingWeeks.max
                  ? `${waiting.waitingWeeks.min} weeks`
                  : `${waiting.waitingWeeks.min}–${waiting.waitingWeeks.max} weeks`}
                {waiting.city && <span className="font-normal text-gray-500"> in {waiting.city}</span>}
              </p>
            ) : (
              <p className="text-sm font-bold text-gray-800 mt-0.5">{waiting.message}</p>
            )}
            {waiting.updatedAt && (
              <p className="text-[10px] text-amber-500 mt-0.5">
                Updated {new Date(waiting.updatedAt).toLocaleDateString("en-IN", { month: "short", year: "numeric" })}
              </p>
            )}
          </div>
        </div>
      )}

      {/* ── Offers / Discounts ── */}
      {hasOffers && (
        <div>
          <div className="flex items-center gap-3 mb-4">
            <BadgePercent className="w-5 h-5 text-green-600" />
            <h3 className="text-base font-black text-gray-900">
              Current Offers & Discounts
            </h3>
            <span className="ml-auto text-xs font-black px-2.5 py-1 rounded-xl bg-green-100 text-green-700">
              {discounts!.offerCount} active
            </span>
          </div>

          {/* by-type summary */}
          {Object.entries(discounts!.byType).length > 0 && (
            <div className="flex flex-wrap gap-2 mb-4">
              {Object.entries(discounts!.byType).map(([type, amt]) => (
                <div
                  key={type}
                  className={`flex items-center gap-1.5 px-3 py-1.5 rounded-xl border text-xs font-bold ${OFFER_COLOR[type] ?? OFFER_COLOR.other}`}
                >
                  <Tag className="w-3 h-3" />
                  {OFFER_LABEL[type] ?? type} · {fmtINR(amt)}
                </div>
              ))}
            </div>
          )}

          <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
            {displayOffers.map((offer) => (
              <div
                key={offer.id}
                className={`rounded-2xl border p-4 ${OFFER_COLOR[offer.type] ?? OFFER_COLOR.other}`}
              >
                <div className="flex items-start justify-between gap-2">
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 mb-1">
                      <span className="text-[10px] font-black uppercase tracking-wide opacity-70">
                        {OFFER_LABEL[offer.type] ?? offer.type}
                      </span>
                      {offer.bankName && (
                        <span className="text-[10px] font-bold opacity-60">· {offer.bankName}</span>
                      )}
                    </div>
                    <p className="text-sm font-black leading-snug">{offer.title}</p>
                    {offer.description && (
                      <p className="text-xs mt-1 opacity-70 leading-relaxed">{offer.description}</p>
                    )}
                    {offer.validTill && (
                      <p className="text-[10px] mt-1.5 opacity-60 flex items-center gap-1">
                        <Clock className="w-3 h-3" />
                        Valid till {new Date(offer.validTill).toLocaleDateString("en-IN", { day: "numeric", month: "short", year: "numeric" })}
                      </p>
                    )}
                  </div>
                  <div className="shrink-0 text-right">
                    <p className="text-base font-black">{fmtINR(offer.amount)}</p>
                    <p className="text-[10px] opacity-60">off</p>
                  </div>
                </div>
              </div>
            ))}
          </div>

          {(discounts?.offers.length ?? 0) > 4 && (
            <button
              onClick={() => setShowAllOffers(!showAllOffers)}
              className="mt-3 w-full py-2.5 text-sm font-bold text-green-700 hover:bg-green-50 rounded-2xl transition-colors flex items-center justify-center gap-1"
            >
              {showAllOffers ? "Show fewer offers" : `See all ${discounts!.offerCount} offers`}
              {showAllOffers ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" />}
            </button>
          )}
        </div>
      )}

      {/* ── Footer ── */}
      <div className="mt-5 pt-4 border-t border-gray-100 flex flex-wrap items-center justify-between gap-3">
        <div className="flex items-center gap-1.5 text-xs text-gray-400">
          <CheckCircle2 className="w-3.5 h-3.5 text-gray-300" />
          Prices include estimated RTO + insurance · visit dealer for exact quote
        </div>
        <Link
          href={`/cities`}
          className="flex items-center gap-1.5 text-xs font-bold text-blue-600 hover:underline"
        >
          <Building2 className="w-3.5 h-3.5" />
          Find dealers near you
        </Link>
      </div>
    </div>
  );
}
