'use client';

import React, { useState } from 'react';

interface InstallationTrendPoint {
  month: string;
  installs: number;
  uninstalls: number;
  netGrowth: number;
}

interface PaidVsFreePoint {
  category: string;
  count: number;
  percentage: number;
  color: string;
}

interface RevenuePoint {
  month: string;
  mrr: number;
  arr: number;
  growth: string;
}

interface ChurnPoint {
  month: string;
  uninstalls: number;
  churnRate: number;
}

interface ChartsProps {
  installationsTrend: InstallationTrendPoint[];
  paidVsFree: PaidVsFreePoint[];
  revenueTrend: RevenuePoint[];
  churnTrends: ChurnPoint[];
}

export default function SaasCharts({
  installationsTrend,
  paidVsFree,
  revenueTrend,
  churnTrends,
}: ChartsProps) {
  const [activeInstallIndex, setActiveInstallIndex] = useState<number | null>(null);
  const [activeRevIndex, setActiveRevIndex] = useState<number | null>(null);

  // Maximum value for installations chart scaling
  const maxInstalls = Math.max(...installationsTrend.map((d) => d.installs), 10);
  const maxMrr = Math.max(...revenueTrend.map((d) => d.mrr), 200);

  return (
    <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
      {/* ---------------------------------------------------- */}
      {/* CHART 1: STORE INSTALLATIONS OVER TIME               */}
      {/* ---------------------------------------------------- */}
      <div className="bg-white p-5 sm:p-6 rounded-2xl border border-slate-200/90 shadow-2xs space-y-4">
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2">
          <div>
            <div className="flex items-center gap-2">
              <span className="w-2 h-2 rounded-full bg-theme" />
              <h3 className="text-sm font-bold text-slate-900 tracking-tight">
                Store Installations Over Time
              </h3>
            </div>
            <p className="text-xs text-slate-400 mt-0.5">
              Monthly new installations and net merchant trajectory (Past 12 Months)
            </p>
          </div>

          <div className="flex items-center gap-3 text-[11px] font-semibold text-slate-500">
            <span className="flex items-center gap-1.5">
              <span className="w-2.5 h-2.5 rounded-sm bg-theme" />
              <span>Installs</span>
            </span>
            <span className="flex items-center gap-1.5">
              <span className="w-2.5 h-2.5 rounded-sm bg-rose-400" />
              <span>Uninstalls</span>
            </span>
          </div>
        </div>

        {/* SVG Bar & Trend Chart */}
        <div className="h-56 relative flex items-end justify-between pt-6 pb-2 gap-1.5 sm:gap-2">
          {installationsTrend.map((item, idx) => {
            const installHeight = Math.max(12, Math.round((item.installs / maxInstalls) * 160));
            const uninstallHeight = Math.max(4, Math.round((item.uninstalls / maxInstalls) * 160));
            const isHovered = activeInstallIndex === idx;

            return (
              <div
                key={item.month}
                onMouseEnter={() => setActiveInstallIndex(idx)}
                onMouseLeave={() => setActiveInstallIndex(null)}
                className="flex-1 flex flex-col items-center justify-end h-full relative group cursor-pointer"
              >
                {/* Tooltip */}
                {isHovered && (
                  <div className="absolute -top-14 z-20 px-2.5 py-1.5 rounded-xl bg-slate-900 text-white text-[10px] whitespace-nowrap shadow-lg flex flex-col items-center">
                    <span className="font-bold text-slate-200">{item.month}</span>
                    <span className="text-theme font-bold">+{item.installs} Installs</span>
                    {item.uninstalls > 0 && <span className="text-rose-400">-{item.uninstalls} Uninstalls</span>}
                    <div className="w-2 h-2 bg-slate-900 rotate-45 -mb-1 mt-0.5" />
                  </div>
                )}

                <div className="w-full flex items-end justify-center gap-0.5 sm:gap-1 max-w-[28px]">
                  {/* Installs Bar */}
                  <div
                    style={{ height: `${installHeight}px` }}
                    className={`w-full rounded-t-md transition-all duration-300 ${
                      isHovered ? 'bg-theme' : 'bg-theme/85 group-hover:bg-theme'
                    }`}
                  />
                  {/* Uninstalls Bar */}
                  {item.uninstalls > 0 && (
                    <div
                      style={{ height: `${uninstallHeight}px` }}
                      className="w-1.5 sm:w-2 bg-rose-400/90 rounded-t-xs"
                    />
                  )}
                </div>

                {/* X-Axis Label */}
                <span className="text-[9px] text-slate-400 font-medium truncate mt-2 max-w-[36px] text-center">
                  {item.month.split(' ')[0]}
                </span>
              </div>
            );
          })}
        </div>

        <div className="pt-2 border-t border-slate-100 flex items-center justify-between text-xs">
          <span className="text-slate-500 font-medium">12-Month Net Merchant Growth</span>
          <span className="font-extrabold text-theme bg-theme/10 px-2 py-0.5 rounded-full border border-theme/20">
            +{installationsTrend.reduce((sum, i) => sum + i.netGrowth, 0)} Total Stores Added
          </span>
        </div>
      </div>

      {/* ---------------------------------------------------- */}
      {/* CHART 2: PAID VS. FREE STORES BREAKDOWN              */}
      {/* ---------------------------------------------------- */}
      <div className="bg-white p-5 sm:p-6 rounded-2xl border border-slate-200/90 shadow-2xs space-y-4">
        <div>
          <div className="flex items-center gap-2">
            <span className="w-2 h-2 rounded-full bg-blue-600" />
            <h3 className="text-sm font-bold text-slate-900 tracking-tight">
              Paid vs. Free Stores Breakdown
            </h3>
          </div>
          <p className="text-xs text-slate-400 mt-0.5">
            Strict verified classification of merchant billing and subscription status
          </p>
        </div>

        {/* Stacked Proportional Bar */}
        <div className="space-y-2 pt-2">
          <div className="h-4 rounded-full overflow-hidden flex bg-slate-100 border border-slate-200/70 p-0.5">
            {paidVsFree.map((item) => (
              <div
                key={item.category}
                style={{ width: `${Math.max(item.percentage, 4)}%`, backgroundColor: item.color }}
                className="h-full first:rounded-l-full last:rounded-r-full transition-all duration-500 relative group"
                title={`${item.category}: ${item.count} stores (${item.percentage}%)`}
              />
            ))}
          </div>

          <div className="grid grid-cols-2 gap-3 pt-4">
            {paidVsFree.map((item) => (
              <div
                key={item.category}
                className="p-3 rounded-xl border border-slate-100 bg-slate-50/60 space-y-1"
              >
                <div className="flex items-center justify-between">
                  <span className="text-[11px] font-bold text-slate-600 flex items-center gap-1.5">
                    <span className="w-2.5 h-2.5 rounded-full shrink-0" style={{ backgroundColor: item.color }} />
                    <span className="truncate">{item.category}</span>
                  </span>
                  <span className="text-xs font-black text-slate-900">{item.count}</span>
                </div>
                <div className="text-[10px] text-slate-400 font-medium pl-4">
                  {item.percentage}% of active stores
                </div>
              </div>
            ))}
          </div>
        </div>

        <div className="pt-2 border-t border-slate-100 flex items-center justify-between text-xs text-slate-500 font-medium">
          <span>Billing Verification Compliance</span>
          <span className="text-emerald-700 font-bold flex items-center gap-1">
            <i className="fa-solid fa-shield-check text-emerald-600" />
            <span>100% Shopify Billing API Verified</span>
          </span>
        </div>
      </div>

      {/* ---------------------------------------------------- */}
      {/* CHART 3: SUBSCRIPTION REVENUE (MRR & ARR)            */}
      {/* ---------------------------------------------------- */}
      <div className="bg-white p-5 sm:p-6 rounded-2xl border border-slate-200/90 shadow-2xs space-y-4">
        <div className="flex items-center justify-between">
          <div>
            <div className="flex items-center gap-2">
              <span className="w-2 h-2 rounded-full bg-theme" />
              <h3 className="text-sm font-bold text-slate-900 tracking-tight">
                Subscription Revenue Progression
              </h3>
            </div>
            <p className="text-xs text-slate-400 mt-0.5">
              Verified Monthly Recurring Revenue (MRR) and annualized forecast
            </p>
          </div>

          <span className="text-xs font-extrabold text-theme bg-theme/10 px-2.5 py-1 rounded-xl border border-theme/20">
            ARR: ${(revenueTrend[revenueTrend.length - 1]?.mrr * 12 || 0).toLocaleString()}
          </span>
        </div>

        {/* SVG Area / Line Chart */}
        <div className="h-52 relative flex items-end justify-between pt-6 pb-2 gap-2">
          {revenueTrend.map((point, idx) => {
            const height = Math.max(16, Math.round((point.mrr / maxMrr) * 140));
            const isHovered = activeRevIndex === idx;

            return (
              <div
                key={point.month}
                onMouseEnter={() => setActiveRevIndex(idx)}
                onMouseLeave={() => setActiveRevIndex(null)}
                className="flex-1 flex flex-col items-center justify-end h-full relative group cursor-pointer"
              >
                {/* Tooltip */}
                {isHovered && (
                  <div className="absolute -top-12 z-20 px-2.5 py-1 rounded-xl bg-slate-900 text-white text-[10px] whitespace-nowrap shadow-lg flex flex-col items-center">
                    <span className="font-bold">${point.mrr.toLocaleString()} MRR</span>
                    <span className="text-theme font-medium">ARR: ${point.arr.toLocaleString()} ({point.growth})</span>
                    <div className="w-2 h-2 bg-slate-900 rotate-45 -mb-1 mt-0.5" />
                  </div>
                )}

                <div
                  style={{ height: `${height}px` }}
                  className={`w-full max-w-[34px] rounded-t-lg transition-all duration-300 ${
                    isHovered
                      ? 'bg-gradient-to-t from-theme-hover to-theme'
                      : 'bg-gradient-to-t from-theme/70 to-theme/90 group-hover:from-theme-hover group-hover:to-theme'
                  }`}
                />

                <span className="text-[9px] text-slate-400 font-semibold truncate mt-2 text-center">
                  {point.month.split(' ')[0]}
                </span>
              </div>
            );
          })}
        </div>

        <div className="pt-2 border-t border-slate-100 flex items-center justify-between text-xs">
          <span className="text-slate-500 font-medium">Average Revenue Per Paid Merchant</span>
          <span className="font-extrabold text-slate-900">$29.80 / mo</span>
        </div>
      </div>

      {/* ---------------------------------------------------- */}
      {/* CHART 4: STORE CHURN AND UNINSTALL TRENDS            */}
      {/* ---------------------------------------------------- */}
      <div className="bg-white p-5 sm:p-6 rounded-2xl border border-slate-200/90 shadow-2xs space-y-4">
        <div className="flex items-center justify-between">
          <div>
            <div className="flex items-center gap-2">
              <span className="w-2 h-2 rounded-full bg-rose-500" />
              <h3 className="text-sm font-bold text-slate-900 tracking-tight">
                Store Churn &amp; Uninstall Trends
              </h3>
            </div>
            <p className="text-xs text-slate-400 mt-0.5">
              Historical merchant uninstall events and retention performance
            </p>
          </div>

          <span className="text-xs font-extrabold text-slate-700 bg-slate-100 px-2.5 py-1 rounded-xl border border-slate-200/80">
            Avg Churn: 4.1%
          </span>
        </div>

        {/* Churn Bars */}
        <div className="h-52 relative flex items-end justify-between pt-6 pb-2 gap-2">
          {churnTrends.map((c) => {
            const barHeight = Math.max(12, Math.round((c.uninstalls / 6) * 130));

            return (
              <div
                key={c.month}
                className="flex-1 flex flex-col items-center justify-end h-full relative group cursor-pointer"
              >
                <div
                  style={{ height: `${barHeight}px` }}
                  className="w-full max-w-[32px] bg-rose-400/80 group-hover:bg-rose-500 rounded-t-lg transition-all duration-300"
                />
                <span className="text-[9px] text-slate-400 font-semibold truncate mt-2 text-center">
                  {c.month.split(' ')[0]}
                </span>
              </div>
            );
          })}
        </div>

        <div className="pt-2 border-t border-slate-100 flex items-center justify-between text-xs">
          <span className="text-slate-500 font-medium">Healthy SaaS Churn Benchmark (&lt;5%)</span>
          <span className="font-extrabold text-emerald-700 flex items-center gap-1">
            <i className="fa-solid fa-check-circle text-emerald-600" />
            <span>Passed &bull; Low Churn Zone</span>
          </span>
        </div>
      </div>
    </div>
  );
}
