'use client';

import React, { useState, useRef } from 'react';
import { Check, X, Sparkles, ChevronLeft, ChevronRight, ArrowRight, HelpCircle } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';

// ── Types ─────────────────────────────────────────────────────────────────────
interface Plan {
  _id: string;
  name: string;
  description?: string;
  planType?: string;
  isPopular?: boolean;
  trialDays?: number;
  billingPeriods?: string[];
  price?: { monthly: number; yearly: number };
  features?: { _id?: string; title: string; included: boolean }[];
  limits?: {
    license?: number;
    languages?: number;
    historyDays?: number;
    liveChatHuman?: boolean;
    branding?: boolean;
    chatbots?: number;
    qnaPairs?: number;
    messagesPerMonth?: number;
    apiCalls?: number;
  };
}

interface Step1Props {
  selectedPlan: string | null;
  setSelectedPlan: (id: string) => void;
  billingPeriod: 'monthly' | 'yearly';
  setBillingPeriod: (p: 'monthly' | 'yearly') => void;
  onNext: () => void;
  validateStep: () => boolean;
  plan: Plan[];
  loadingState?: boolean;
}

// ── Helpers ───────────────────────────────────────────────────────────────────
const formatPrice = (price: number) =>
  new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', minimumFractionDigits: 0, maximumFractionDigits: 0 }).format(price);

const formatLimitValue = (value: any) => {
  if (value === undefined || value === null) return '—';
  if (value === -1 || value === Infinity) return 'Unlimited';
  if (typeof value === 'boolean') return value ? 'Yes' : 'No';
  if (typeof value === 'number') {
    // Convert numbers to strings with proper formatting
    return value.toLocaleString();
  }
  return String(value);
};

const PLAN_COLORS: Record<string, { badge: string; accent: string; ring: string }> = {
  starter: { badge: 'bg-emerald-100 text-emerald-700 border-emerald-200', accent: 'from-emerald-500 to-teal-500', ring: 'ring-emerald-400' },
  growth: { badge: 'bg-blue-100 text-blue-700 border-blue-200', accent: 'from-blue-500 to-cyan-500', ring: 'ring-blue-400' },
  business: { badge: 'bg-violet-100 text-violet-700 border-violet-200', accent: 'from-violet-500 to-purple-500', ring: 'ring-violet-400' },
  enterprise: { badge: 'bg-orange-100 text-orange-700 border-orange-200', accent: 'from-orange-500 to-amber-500', ring: 'ring-orange-400' },
};

const getPlanColor = (type = '') => {
  const key = Object.keys(PLAN_COLORS).find(k => type.toLowerCase().includes(k));
  return PLAN_COLORS[key || ''] || { badge: 'bg-gray-100 text-gray-700 border-gray-200', accent: 'from-gray-500 to-slate-500', ring: 'ring-gray-400' };
};

// Collect ALL unique feature titles across all plans
const getAllFeatures = (plans: Plan[]) => {
  const map = new Map<string, string>();
  plans.forEach(p =>
    p.features?.forEach((f) => {
      if (!map.has(f.title)) map.set(f.title, '');
    })
  );
  return Array.from(map.keys());
};

// ── PlanCard ──────────────────────────────────────────────────────────────────
const PlanCard = ({ plan, selected, onSelect, billingPeriod, allFeatures }: {
  plan: Plan; selected: boolean; onSelect: (id: string) => void; billingPeriod: 'monthly' | 'yearly'; allFeatures: string[];
}) => {
  const price = billingPeriod === 'yearly' ? plan.price?.yearly ?? 0 : plan.price?.monthly ?? 0;
  const colors = getPlanColor(plan.planType);

  // Build a lookup for this plan's features
  const featureMap = new Map(plan.features?.map(f => [f.title, f.included]) ?? []);

  return (
    <div className={cn(
      'relative flex flex-col rounded-2xl border-2 bg-white transition-all duration-300 cursor-pointer group overflow-hidden',
      'w-[300px] flex-shrink-0 snap-start',
      selected
        ? `border-transparent ring-2 ${colors.ring} shadow-xl shadow-black/10 scale-[1.02]`
        : 'border-gray-100 hover:border-gray-200 hover:shadow-lg',
      plan.isPopular ? 'ring-2 ring-offset-2 ring-blue-400' : ''
    )} onClick={() => onSelect(plan._id)}>
      {/* Top accent bar */}
      <div className={cn('h-1.5 w-full bg-gradient-to-r', colors.accent)} />

      {plan.isPopular && (
        <div className="absolute top-4 right-4">
          <span className={cn('inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-bold text-white bg-gradient-to-r', colors.accent)}>
            <Sparkles className="w-3 h-3" /> Popular
          </span>
        </div>
      )}

      <div className="p-6 flex flex-col flex-1">
        {/* Header */}
        <div className="mb-2">
          <div className="flex items-center gap-2 mb-1">
            <span className={cn('text-xs font-semibold px-2 py-0.5 rounded-full border', colors.badge)}>
              {plan.planType?.replace(/[-_]/g, ' ').replace(/\b\w/g, c => c.toUpperCase()) || 'Plan'}
            </span>
          </div>
          <h3 className="text-xl font-bold text-gray-900 mt-2">{plan.name}</h3>
          {plan.description && <p className="text-gray-500 text-sm mt-1 leading-relaxed">{plan.description}</p>}
        </div>

        {/* Pricing */}
        <div className="mb-2">
          <div className="flex items-end gap-1">
            <span className="text-4xl font-black text-gray-900 tracking-tight">{formatPrice(price)}</span>
            <span className="text-gray-400 text-sm mb-1.5">/{billingPeriod === 'yearly' ? 'yr' : 'mo'}</span>
          </div>
        </div>

        {/* Features — show ALL global features with check or cross */}
        <ul className="space-y-2 mb-2 flex-1">
          {allFeatures.map((title) => {
            // featureMap has the feature with its included value if plan has it
            // If the plan doesn't have it at all, treat as not included
            const included = featureMap.get(title) ?? false;
            return (
              <li key={title} className="flex items-start gap-2">
                {included ? (
                  <Check className="w-4 h-4 mt-0.5 flex-shrink-0 text-emerald-500" />
                ) : (
                  <X className="w-4 h-4 mt-0.5 flex-shrink-0 text-red-400" />
                )}
                <span className={cn('text-sm', included ? 'text-gray-700' : 'text-gray-400')}>
                  {title}
                </span>
              </li>
            );
          })}
        </ul>

        {/* Limits grid */}
        {plan.limits && (
          <div className="grid grid-cols-2 gap-2 mb-2">
            {[
              { label: 'Chatbots', val: plan.limits.license },
              { label: 'Languages', val: plan.limits.languages },
              { label: 'History Days', val: plan.limits.historyDays },
              { label: 'Live Chat', val: plan.limits.liveChatHuman },
            ].map(({ label, val }) => (
              <div key={label} className="bg-gray-50 rounded-lg p-2.5 border border-gray-100">
                <div className="text-xs text-gray-400 mb-0.5">{label}</div>
                <div className="font-semibold text-gray-900 text-sm">{formatLimitValue(val)}</div>
              </div>
            ))}
          </div>
        )}

        {/* Select button */}
        <Button
          onClick={(e) => { e.stopPropagation(); onSelect(plan._id); }}
          className={cn(
            'w-full font-semibold rounded-xl transition-all cursor-pointer',
            selected
              ? `bg-gradient-to-r ${colors.accent} text-white hover:opacity-90 shadow-lg`
              : 'bg-gray-100 text-gray-800 hover:bg-gray-200'
          )}
        >
          {selected ? (
            <span className="flex items-center justify-center gap-1.5">
              <Check className="w-4 h-4" /> Selected
            </span>
          ) : 'Select Plan'}
        </Button>
      </div>
    </div>
  );
};

// ── Billing Toggle ─────────────────────────────────────────────────────────────
const BillingToggle = ({ billingPeriod, setBillingPeriod }: {
  billingPeriod: 'monthly' | 'yearly'; setBillingPeriod: (p: 'monthly' | 'yearly') => void;
}) => (
  <div className="inline-flex items-center bg-gray-100 rounded-full p-1 gap-0.5">
    {(['monthly', 'yearly'] as const).map((p) => (
      <button
        key={p}
        onClick={() => setBillingPeriod(p)}
        className={cn(
          'px-5 py-2 rounded-full text-sm font-semibold transition-all duration-200 cursor-pointer',
          billingPeriod === p
            ? 'bg-white text-gray-900 shadow-sm'
            : 'text-gray-500 hover:text-gray-700'
        )}
      >
        {p.charAt(0).toUpperCase() + p.slice(1)}
      </button>
    ))}
  </div>
);

// ── Main Component ─────────────────────────────────────────────────────────────
export default function Step1PlanSelection({
  selectedPlan, setSelectedPlan, billingPeriod, setBillingPeriod,
  onNext, validateStep, plan: plans = [], loadingState = false,
}: Step1Props) {
  const scrollRef = useRef<HTMLDivElement>(null);
  const comparisonRef = useRef<HTMLDivElement>(null);
  const [comparisonOpen, setComparisonOpen] = useState(false);
  const [canScrollLeft, setCanScrollLeft] = useState(false);
  const [canScrollRight, setCanScrollRight] = useState(true);

  const selectedPlanData = plans.find(p => p._id === selectedPlan);

  // Compute global feature list once
  const allFeatures = React.useMemo(() => getAllFeatures(plans), [plans]);

  const scroll = (dir: 'left' | 'right') => {
    if (!scrollRef.current) return;
    scrollRef.current.scrollBy({ left: dir === 'right' ? 320 : -320, behavior: 'smooth' });
  };

  const handleScroll = () => {
    const el = scrollRef.current;
    if (!el) return;
    setCanScrollLeft(el.scrollLeft > 0);
    setCanScrollRight(el.scrollLeft + el.clientWidth < el.scrollWidth - 4);
  };

  const handleNext = () => { if (validateStep()) onNext(); };

  const toggleComparison = () => {
    if (!comparisonOpen) {
      // Opening the comparison
      setComparisonOpen(true);
      // Use setTimeout to ensure the DOM has updated with the comparison table
      setTimeout(() => {
        if (comparisonRef.current) {
          comparisonRef.current.scrollIntoView({ 
            behavior: 'smooth', 
            block: 'start' 
          });
        }
      }, 100);
    } else {
      setComparisonOpen(false);
    }
  };

  // Returns true/false/null — null means plan doesn't have this feature at all
  const getFeatureStatus = (plan: Plan, title: string): boolean => {
    const feature = plan.features?.find(f => f.title === title);
    if (!feature) return false; // not present → cross
    return feature.included;
  };

  if (loadingState) {
    return (
      <div className="min-h-[60vh] flex items-center justify-center">
        <div className="text-center">
          <div className="w-12 h-12 border-4 border-blue-200 border-t-blue-600 rounded-full animate-spin mx-auto" />
          <p className="mt-4 text-gray-500 font-medium">Loading plans…</p>
        </div>
      </div>
    );
  }

  return (
    <div className="w-full">
      {/* Header */}
      <div className="text-center mb-10">
        <h1 className="text-4xl font-black text-gray-900 mb-3 tracking-tight">
          Choose Your Plan
        </h1>
      </div>

      {/* ── Global Billing Toggle ── */}
      <div className="flex justify-center mb-8">
        <BillingToggle billingPeriod={billingPeriod} setBillingPeriod={setBillingPeriod} />
      </div>

      {/* ── Horizontal Scrollable Cards ── */}
      <div className="relative">
        {canScrollLeft && (
          <button
            onClick={() => scroll('left')}
            className="absolute left-0 top-1/2 -translate-y-1/2 -translate-x-4 z-10 w-10 h-10 rounded-full bg-white border border-gray-200 shadow-lg flex items-center justify-center hover:bg-gray-50 transition cursor-pointer"
          >
            <ChevronLeft className="w-5 h-5 text-gray-600" />
          </button>
        )}

        {canScrollRight && (
          <button
            onClick={() => scroll('right')}
            className="absolute right-0 top-1/2 -translate-y-1/2 translate-x-4 z-10 w-10 h-10 rounded-full bg-white border border-gray-200 shadow-lg flex items-center justify-center hover:bg-gray-50 transition cursor-pointer"
          >
            <ChevronRight className="w-5 h-5 text-gray-600" />
          </button>
        )}

        <div
          ref={scrollRef}
          onScroll={handleScroll}
          className="flex gap-5 overflow-x-auto scroll-smooth snap-x snap-mandatory pb-4 px-1"
          style={{ scrollbarWidth: 'none', msOverflowStyle: 'none' }}
        >
          {plans.map(p => (
            <PlanCard
              key={p._id}
              plan={p}
              selected={selectedPlan === p._id}
              onSelect={setSelectedPlan}
              billingPeriod={billingPeriod}
              allFeatures={allFeatures}
            />
          ))}
        </div>
      </div>

      {/* ── Selected Plan Summary ── */}
      {selectedPlanData && (
        <div className="mt-8 bg-gradient-to-r from-blue-50 via-indigo-50 to-blue-50 rounded-2xl border border-blue-200 p-6 flex flex-col sm:flex-row sm:items-center justify-between gap-4 shadow-sm">
          <div>
            <p className="text-sm text-gray-500 font-medium mb-0.5">Selected Plan</p>
            <h3 className="text-xl font-bold text-gray-900">
              {selectedPlanData.name}
              <span className="ml-2 text-blue-600 text-lg font-semibold">
                {billingPeriod === 'yearly'
                  ? formatPrice(selectedPlanData.price?.yearly ?? 0) + '/yr'
                  : formatPrice(selectedPlanData.price?.monthly ?? 0) + '/mo'}
              </span>
            </h3>
          </div>
          <Button
            onClick={handleNext}
            size="lg"
            className="bg-blue-600 hover:bg-blue-700 text-white font-bold rounded-xl px-8 shadow-lg shadow-blue-200 cursor-pointer"
          >
            Continue to Setup
            <ArrowRight className="ml-2 w-5 h-5" />
          </Button>
        </div>
      )}

      {/* ── Compare Plans Toggle ── */}
      <div className="mt-8 text-center">
        <button
          onClick={toggleComparison}
          className="inline-flex items-center gap-2 text-blue-600 hover:text-blue-800 font-medium text-sm transition-colors cursor-pointer"
        >
          <HelpCircle className="w-4 h-4" />
          {comparisonOpen ? 'Hide comparison' : 'Compare all plans'}
        </button>
      </div>

      {/* ── Comparison Table ── */}
      {comparisonOpen && (
        <div 
          ref={comparisonRef}
          className="mt-6 bg-white rounded-2xl border border-gray-200 overflow-hidden shadow-lg"
        >
          <div className="overflow-x-auto">
            <table className="w-full min-w-[700px] text-sm">
              <thead>
                <tr className="bg-gray-50 border-b border-gray-200">
                  <th className="p-4 text-left font-semibold text-gray-700">Feature</th>
                  {plans.map(p => (
                    <th key={p._id} className="p-4 text-center">
                      <div className="font-bold text-gray-900">{p.name}</div>
                      <div className="text-gray-500 text-xs mt-0.5 font-normal">
                        {billingPeriod === 'yearly'
                          ? formatPrice(p.price?.yearly ?? 0) + '/yr'
                          : formatPrice(p.price?.monthly ?? 0) + '/mo'}
                      </div>
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-100">

                {/* ── Limits section ── */}
                <tr className="bg-gray-50/70">
                  <td colSpan={plans.length + 1} className="px-4 py-2 text-xs font-bold text-gray-500 uppercase tracking-wider">
                    Limits
                  </td>
                </tr>
                {[
                  { label: 'Chatbots', key: 'license' },
                  { label: 'Languages', key: 'languages' },
                  { label: 'History Days', key: 'historyDays' },
                  { label: 'Live Chat Human Handoff', key: 'liveChatHuman' },
                  { label: 'Custom Branding', key: 'branding' },
                ].map(({ label, key }) => (
                  <tr key={key} className="hover:bg-gray-50">
                    <td className="p-4 font-medium text-gray-700">{label}</td>
                    {plans.map(p => {
                      const val = (p.limits as any)?.[key];
                      return (
                        <td key={p._id} className="p-4 text-center  text-gray-900">
                          {formatLimitValue(val)}
                        </td>
                      );
                    })}
                  </tr>
                ))}

                {/* ── Features section ── */}
                <tr className="bg-gray-50/70">
                  <td colSpan={plans.length + 1} className="px-4 py-2 text-xs font-bold text-gray-500 uppercase tracking-wider">
                    Features
                  </td>
                </tr>
                {allFeatures.map((title, i) => (
                  <tr key={i} className="hover:bg-gray-50">
                    <td className="p-4 text-gray-700 font-medium">{title}</td>
                    {plans.map(p => {
                      const included = getFeatureStatus(p, title);
                      return (
                        <td key={p._id} className="p-4 text-center">
                          {included ? (
                            <span className="inline-flex items-center justify-center w-7 h-7 rounded-full bg-emerald-100 text-emerald-600">
                              <Check className="w-4 h-4" />
                            </span>
                          ) : (
                            <span className="inline-flex items-center justify-center w-7 h-7 rounded-full bg-red-50 text-red-400">
                              <X className="w-4 h-4" />
                            </span>
                          )}
                        </td>
                      );
                    })}
                  </tr>
                ))}

              </tbody>
            </table>
          </div>
          <div className="p-4 text-center border-t border-gray-100">
            <button
              onClick={() => setComparisonOpen(false)}
              className="inline-flex items-center gap-1.5 text-gray-500 hover:text-gray-700 text-sm cursor-pointer"
            >
              <X className="w-4 h-4" /> Close comparison
            </button>
          </div>
        </div>
      )}
    </div>
  );
}