"use client";

import { useState, useMemo } from "react";
import { motion } from "framer-motion";
import Container from "@/components/shared/Container";
import AnimateOnScroll from "@/components/shared/AnimateOnScroll";
import { content } from "@/lib/content";

const pricing = content.ar.pricing;

const PLANS = pricing.plans.map((p) => ({
  name: p.name,
  subscription: p.priceNumeric,
  feePercent: p.platformFeeNumeric,
}));

const MIN_COLLECTIONS = 10000;
const MAX_COLLECTIONS = 500000;
const STEP = 5000;

function formatMoney(amount: number): string {
  return amount.toLocaleString("ar-EG") + " ج.م.";
}

export default function PricingCalculator() {
  const [collections, setCollections] = useState(460000);

  const calculations = useMemo(() => {
    return PLANS.map((plan) => {
      const commission = Math.round(collections * plan.feePercent);
      const total = plan.subscription + commission;
      return {
        name: plan.name,
        subscription: plan.subscription,
        feePercent: plan.feePercent,
        commission,
        total,
      };
    });
  }, [collections]);

  const bestValueIndex = useMemo(() => {
    let minTotal = Infinity;
    let bestIdx = 0;
    calculations.forEach((calc, idx) => {
      if (calc.total < minTotal) {
        minTotal = calc.total;
        bestIdx = idx;
      }
    });
    return bestIdx;
  }, [calculations]);

  return (
    <section className="py-16 bg-slate-50">
      <Container className="max-w-3xl">
        <AnimateOnScroll>
          <div className="text-center mb-10">
            <h2 className="text-2xl sm:text-3xl font-bold text-navy-800">
              {pricing.calculatorTitle}: {formatMoney(collections)}
            </h2>
          </div>

          {/* Slider */}
          <div className="mb-10 px-2">
            <input
              type="range"
              min={MIN_COLLECTIONS}
              max={MAX_COLLECTIONS}
              step={STEP}
              value={collections}
              onChange={(e) => setCollections(Number(e.target.value))}
              className="w-full h-2 bg-slate-200 rounded-lg appearance-none cursor-pointer accent-navy-800
                [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-5 [&::-webkit-slider-thumb]:h-5
                [&::-webkit-slider-thumb]:bg-navy-800 [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:cursor-pointer
                [&::-moz-range-thumb]:w-5 [&::-moz-range-thumb]:h-5 [&::-moz-range-thumb]:bg-navy-800
                [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:border-0 [&::-moz-range-thumb]:cursor-pointer"
              dir="ltr"
            />
            <div className="flex justify-between mt-2 text-xs text-slate-500" dir="ltr">
              <span>{formatMoney(MIN_COLLECTIONS)}</span>
              <span>{formatMoney(MAX_COLLECTIONS)}</span>
            </div>
          </div>

          {/* Plan Cards */}
          <div className="space-y-4">
            {calculations.map((calc, index) => {
              const isBest = index === bestValueIndex;
              return (
                <motion.div
                  key={calc.name}
                  layout
                  className={`relative rounded-2xl border-2 bg-white p-5 sm:p-6 transition-all ${
                    isBest
                      ? "border-navy-800 shadow-lg"
                      : "border-slate-200"
                  }`}
                >
                  {isBest && (
                    <span className="absolute -top-3 start-4 inline-flex items-center rounded-full bg-teal-500 px-3 py-0.5 text-xs font-semibold text-white">
                      {pricing.bestValueBadge}
                    </span>
                  )}

                  <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
                    <h3 className="text-lg font-bold text-navy-800">
                      {calc.name}
                    </h3>

                    <div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-sm text-slate-600">
                      <span>
                        اشتراك: {formatMoney(calc.subscription)}
                      </span>
                      <span>
                        عمولة: {formatMoney(calc.commission)} ({(calc.feePercent * 100).toFixed(calc.feePercent * 100 % 1 === 0 ? 0 : 1)}%)
                      </span>
                    </div>
                  </div>

                  <div className="mt-3 text-end">
                    <span className="text-2xl font-black text-navy-800">
                      {formatMoney(calc.total)}
                    </span>
                  </div>
                </motion.div>
              );
            })}
          </div>
        </AnimateOnScroll>
      </Container>
    </section>
  );
}
