import React, { useState } from 'react';
import {
  Calculator,
  X,
  CheckCircle2,
  Sparkles,
  CreditCard,
  Building,
  HelpCircle,
  ArrowRight,
  ShieldCheck,
  MessageCircle,
  Percent,
  Calendar,
  Gift,
  Coins,
  ChevronRight,
  ExternalLink,
  Check
} from 'lucide-react';
import { COURSES, ZiteCourse, findCourseBySlug, SUBJECTS } from '../data/courses';
import {
  Currency,
  CoursePricing,
  PaymentPlanType,
  getPricingForCourse,
  formatMoney,
  calculatePaymentPlans,
  CalculatedPlan,
} from '../data/pricing';
import { getCohortForCourse } from '../data/cohorts';
import { Container, Eyebrow } from './Ui';

interface TuitionCalculatorProps {
  initialCourseSlug?: string;
  isModal?: boolean;
  isOpen?: boolean;
  onClose?: () => void;
  onNavigate: (path: string) => void;
}

export function TuitionCalculator({
  initialCourseSlug = 'aws-cloud-practitioner-preparation',
  isModal = false,
  isOpen = true,
  onClose,
  onNavigate,
}: TuitionCalculatorProps) {
  const [selectedSlug, setSelectedSlug] = useState<string>(initialCourseSlug);
  const [currency, setCurrency] = useState<Currency>('KES');
  const [selectedPlanType, setSelectedPlanType] = useState<PaymentPlanType>('full');

  if (isModal && !isOpen) return null;

  const currentCourse = findCourseBySlug(selectedSlug) || COURSES[0];
  const meta = SUBJECTS[currentCourse.subject];
  const pricing = getPricingForCourse(currentCourse.slug);
  const plans = calculatePaymentPlans(pricing, currency);
  const activePlan = plans.find((p) => p.planType === selectedPlanType) || plans[0];
  const cohort = getCohortForCourse(currentCourse.slug);

  const handleEnrolWithPlan = () => {
    if (onClose) onClose();
    const query = new URLSearchParams({
      mode: activePlan.planType === 'sponsorship' ? 'guidance' : 'learner',
      course: currentCourse.slug,
      plan: activePlan.planType,
      currency,
    }).toString();
    onNavigate(`/contact?${query}`);
  };

  const handleApplySponsorship = () => {
    if (onClose) onClose();
    const query = new URLSearchParams({
      mode: 'guidance',
      course: currentCourse.slug,
      topic: 'sponsorship-application',
      currency,
    }).toString();
    onNavigate(`/contact?${query}`);
  };

  const whatsappMessage = encodeURIComponent(
    `Hello PANIA Admissions, I am interested in the ${currentCourse.title} programme using the ${activePlan.title} (${formatMoney(
      activePlan.totalAmount,
      currency
    )}). Could you guide me through my enrolment steps?`
  );

  const content = (
    <div className="space-y-8">
      {/* Header */}
      <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 pb-6 border-b border-border">
        <div className="flex items-center gap-3">
          <span className="w-12 h-12 rounded-2xl bg-primary text-primary-foreground flex items-center justify-center shadow-xs">
            <Calculator className="w-6 h-6" />
          </span>
          <div>
            <div className="flex items-center gap-2">
              <h2 className="text-xl sm:text-2xl font-bold tracking-tight text-foreground">
                Tuition & Flexible Payment Calculator
              </h2>
              <span className="text-xs font-bold px-2.5 py-0.5 rounded-full bg-accent text-accent-foreground">
                Zero Hidden Fees
              </span>
            </div>
            <p className="text-xs sm:text-sm text-muted-foreground mt-0.5">
              Transparent, milestone-based fees with early bird waivers and regional financial aid.
            </p>
          </div>
        </div>

        {/* Currency Switcher Pill */}
        <div className="flex items-center gap-1.5 p-1 rounded-2xl bg-secondary/80 border border-border shrink-0 self-end sm:self-auto">
          <button
            onClick={() => setCurrency('KES')}
            className={`px-3 py-1.5 rounded-xl text-xs font-bold transition-all cursor-pointer flex items-center gap-1.5 ${
              currency === 'KES'
                ? 'bg-primary text-primary-foreground shadow-xs'
                : 'text-muted-foreground hover:text-foreground'
            }`}
          >
            <span>🇰🇪 KES (Shilling)</span>
          </button>
          <button
            onClick={() => setCurrency('USD')}
            className={`px-3 py-1.5 rounded-xl text-xs font-bold transition-all cursor-pointer flex items-center gap-1.5 ${
              currency === 'USD'
                ? 'bg-primary text-primary-foreground shadow-xs'
                : 'text-muted-foreground hover:text-foreground'
            }`}
          >
            <span>🌐 USD ($)</span>
          </button>
        </div>
      </div>

      {/* Select Course Row */}
      <div className="grid sm:grid-cols-12 gap-4 items-center bg-secondary/40 p-4 sm:p-5 rounded-2xl border border-border/80">
        <div className="sm:col-span-4 space-y-1">
          <label className="text-xs font-bold text-foreground flex items-center gap-1.5">
            <span>Select Programme:</span>
          </label>
          <p className="text-[11px] text-muted-foreground">
            Choose from all 22 live online certification pathways
          </p>
        </div>

        <div className="sm:col-span-8 flex flex-col sm:flex-row gap-3 items-stretch sm:items-center">
          <select
            value={selectedSlug}
            onChange={(e) => {
              setSelectedSlug(e.target.value);
              setSelectedPlanType('full');
            }}
            className="flex-1 text-sm font-semibold px-4 py-2.5 rounded-xl bg-card border border-border text-foreground cursor-pointer focus:ring-2 focus:ring-primary focus:outline-hidden"
          >
            {COURSES.map((c) => (
              <option key={c.code} value={c.slug}>
                {c.title} ({c.provider} · {c.subject.toUpperCase()})
              </option>
            ))}
          </select>

          <div className="flex items-center gap-2 shrink-0">
            <span
              className={`text-[11px] font-bold px-2.5 py-1.5 rounded-xl ${meta.bgSoft} ${meta.textColor}`}
            >
              {pricing.durationWeeks} Weeks
            </span>
            {cohort && (
              <span className="text-[11px] font-bold px-2.5 py-1.5 rounded-xl bg-teal-soft text-teal border border-teal/20">
                Admissions Open
              </span>
            )}
          </div>
        </div>
      </div>

      {/* Plan Selection Cards Grid */}
      <div className="space-y-3">
        <div className="flex items-center justify-between">
          <p className="text-xs font-bold uppercase tracking-wider text-muted-foreground">
            Choose Your Payment Structure:
          </p>
          <span className="text-xs text-primary font-semibold">
            {currency === 'KES' ? 'M-Pesa · Equity · KCB · NCBA' : 'Visa · MasterCard · PayPal · Wire'}
          </span>
        </div>

        <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
          {plans.map((plan) => {
            const isSelected = selectedPlanType === plan.planType;
            const isSponsorship = plan.planType === 'sponsorship';

            return (
              <div
                key={plan.planType}
                onClick={() => setSelectedPlanType(plan.planType)}
                className={`p-5 rounded-3xl border transition-all duration-200 cursor-pointer flex flex-col justify-between relative ${
                  isSelected
                    ? 'bg-card border-primary ring-2 ring-primary/30 shadow-md -translate-y-0.5'
                    : 'bg-card/70 border-border hover:border-primary/40 hover:bg-card shadow-xs'
                }`}
              >
                <div>
                  {/* Top Badge */}
                  <div className="flex items-center justify-between gap-2 mb-3">
                    <span
                      className={`text-[11px] font-bold px-2.5 py-0.5 rounded-full ${
                        isSponsorship
                          ? 'bg-teal/10 text-teal border border-teal/20'
                          : plan.planType === 'full'
                          ? 'bg-accent text-accent-foreground font-black'
                          : 'bg-secondary text-foreground'
                      }`}
                    >
                      {plan.badge}
                    </span>

                    <span
                      className={`w-5 h-5 rounded-full flex items-center justify-center transition-colors ${
                        isSelected
                          ? 'bg-primary text-primary-foreground'
                          : 'border border-border text-transparent'
                      }`}
                    >
                      <Check className="w-3 h-3" />
                    </span>
                  </div>

                  {/* Plan Title */}
                  <h3 className="font-bold text-base text-foreground">{plan.title}</h3>

                  {/* Price Header */}
                  <div className="mt-3 space-y-0.5">
                    <div className="flex items-baseline gap-2">
                      <span className="text-2xl sm:text-3xl font-extrabold text-foreground tracking-tight">
                        {formatMoney(plan.totalAmount, currency)}
                      </span>
                      {plan.savings > 0 && (
                        <span className="text-xs text-muted-foreground line-through">
                          {formatMoney(plan.totalAmount + plan.savings, currency)}
                        </span>
                      )}
                    </div>
                    {plan.savings > 0 && (
                      <p className="text-[11px] font-bold text-emerald-600 dark:text-emerald-400">
                        {isSponsorship
                          ? `Financial aid saves ${formatMoney(plan.savings, currency)}`
                          : `Early bird saves ${formatMoney(plan.savings, currency)} (10% off)`}
                      </p>
                    )}
                  </div>

                  {/* Installment breakdown steps */}
                  <div className="mt-4 pt-3 border-t border-border/60 space-y-2">
                    <p className="text-[11px] font-bold text-muted-foreground uppercase">
                      Payment Schedule:
                    </p>
                    <div className="space-y-1.5">
                      {plan.installments.map((inst, idx) => (
                        <div
                          key={idx}
                          className="p-2 rounded-xl bg-secondary/50 text-xs flex items-center justify-between"
                        >
                          <div>
                            <span className="font-semibold text-foreground block">
                              {inst.label}
                            </span>
                            <span className="text-[10px] text-muted-foreground">
                              {inst.dueWhen}
                            </span>
                          </div>
                          <span className="font-bold text-primary shrink-0 ml-2">
                            {formatMoney(inst.amount, currency)}
                          </span>
                        </div>
                      ))}
                    </div>
                  </div>
                </div>

                {/* Features list */}
                <div className="mt-5 pt-3 border-t border-border/60 space-y-1.5">
                  {plan.features.map((feat, idx) => (
                    <div key={idx} className="flex items-start gap-1.5 text-[11px] text-muted-foreground">
                      <CheckCircle2 className="w-3.5 h-3.5 text-teal shrink-0 mt-0.5" />
                      <span>{feat}</span>
                    </div>
                  ))}
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* Selected Plan Details & Action Callout */}
      <div className="p-6 rounded-3xl bg-gradient-to-r from-[#0B4035] to-[#1B365D] text-white shadow-xl relative overflow-hidden">
        <div className="absolute right-0 bottom-0 w-64 h-64 bg-[#D5E64D]/10 rounded-full blur-3xl" />

        <div className="relative z-10 flex flex-col lg:flex-row items-center justify-between gap-6">
          <div className="space-y-2 text-center lg:text-left">
            <div className="flex flex-wrap items-center justify-center lg:justify-start gap-2">
              <span className="text-xs font-bold px-3 py-1 rounded-full bg-white/10 text-[#D5E64D]">
                Selected: {activePlan.title}
              </span>
              <span className="text-xs text-stone-300">
                Course: {currentCourse.title}
              </span>
            </div>

            <h3 className="text-2xl sm:text-3xl font-extrabold tracking-tight text-white">
              Total Tuition: {formatMoney(activePlan.totalAmount, currency)}
            </h3>

            <p className="text-xs sm:text-sm text-stone-300 max-w-xl leading-relaxed">
              {activePlan.description}
            </p>
          </div>

          {/* Action Buttons */}
          <div className="flex flex-col sm:flex-row items-center gap-3 shrink-0 w-full lg:w-auto">
            {activePlan.planType === 'sponsorship' ? (
              <button
                onClick={handleApplySponsorship}
                className="w-full sm:w-auto px-6 py-3.5 rounded-full text-xs sm:text-sm font-bold bg-[#D5E64D] text-[#072C24] hover:bg-white hover:text-black transition shadow-lg flex items-center justify-center gap-2 cursor-pointer font-sans"
              >
                <span>Apply for Financial Aid Grant</span>
                <ArrowRight className="w-4 h-4" />
              </button>
            ) : (
              <button
                onClick={handleEnrolWithPlan}
                className="w-full sm:w-auto px-6 py-3.5 rounded-full text-xs sm:text-sm font-bold bg-[#D5E64D] text-[#072C24] hover:bg-white hover:text-black transition shadow-lg flex items-center justify-center gap-2 cursor-pointer font-sans"
              >
                <span>Lock In This Plan & Enrol</span>
                <ArrowRight className="w-4 h-4" />
              </button>
            )}

            <a
              href={`https://wa.me/254101936893?text=${whatsappMessage}`}
              target="_blank"
              rel="noopener noreferrer"
              className="w-full sm:w-auto px-5 py-3.5 rounded-full text-xs font-semibold bg-white/10 hover:bg-white/20 text-white transition flex items-center justify-center gap-2 cursor-pointer"
            >
              <MessageCircle className="w-4 h-4 text-[#25D366]" />
              <span>Confirm on WhatsApp</span>
            </a>
          </div>
        </div>
      </div>

      {/* Trust & Guarantee Strip */}
      <div className="grid sm:grid-cols-3 gap-4 pt-2">
        <div className="p-4 rounded-2xl bg-secondary/50 border border-border/60 flex items-start gap-3">
          <ShieldCheck className="w-5 h-5 text-teal shrink-0 mt-0.5" />
          <div className="space-y-0.5">
            <p className="font-bold text-xs text-foreground">7-Day Orientation Refund</p>
            <p className="text-[11px] text-muted-foreground">
              If the online learning experience isn't right for you after the first week, receive a full refund.
            </p>
          </div>
        </div>

        <div className="p-4 rounded-2xl bg-secondary/50 border border-border/60 flex items-start gap-3">
          <CreditCard className="w-5 h-5 text-primary shrink-0 mt-0.5" />
          <div className="space-y-0.5">
            <p className="font-bold text-xs text-foreground">Flexible Local & Global Rails</p>
            <p className="text-[11px] text-muted-foreground">
              Instant M-Pesa Buy Goods & Paybill, KCB/Equity bank transfers, and Visa/Mastercard processing.
            </p>
          </div>
        </div>

        <div className="p-4 rounded-2xl bg-secondary/50 border border-border/60 flex items-start gap-3">
          <Gift className="w-5 h-5 text-accent shrink-0 mt-0.5" />
          <div className="space-y-0.5">
            <p className="font-bold text-xs text-foreground">Employer / Team Sponsorship</p>
            <p className="text-[11px] text-muted-foreground">
              Request formal corporate invoices, vendor tax documentation, or group cohort discounts.
            </p>
          </div>
        </div>

        {/* Indicative tuition disclosure */}
        <div className="p-3.5 rounded-2xl bg-secondary/80 border border-border text-xs text-muted-foreground leading-relaxed sm:col-span-3">
          <p>
            <strong className="text-foreground">Admissions Tuition Notice:</strong> Displayed figures and installment models are indicative educational estimates. Official approved fee schedules, local settlement terms, and corporate group rates are confirmed directly by admissions upon enquiry.
          </p>
        </div>
      </div>
    </div>
  );

  if (isModal) {
    return (
      <div className="fixed inset-0 z-50 overflow-y-auto bg-black/75 backdrop-blur-sm animate-in fade-in duration-200 flex flex-col justify-end sm:justify-center p-0 sm:p-4 lg:p-6">
        <div className="bg-card w-full max-w-5xl mx-auto rounded-t-3xl sm:rounded-3xl shadow-2xl border border-border p-6 sm:p-8 max-h-[92vh] overflow-y-auto relative">
          {onClose && (
            <button
              onClick={onClose}
              className="absolute top-5 right-5 w-9 h-9 rounded-full bg-secondary hover:bg-muted text-foreground flex items-center justify-center transition cursor-pointer"
              aria-label="Close calculator modal"
            >
              <X className="w-5 h-5" />
            </button>
          )}
          {content}
        </div>
      </div>
    );
  }

  return (
    <section id="tuition" className="py-20 bg-background relative overflow-hidden border-t border-border">
      <Container>{content}</Container>
    </section>
  );
}
