'use client';

import { useState } from 'react';

/**
 * ChartCard — Card wrapper for chart widgets.
 *
 * Features:
 * - Title with auto-selected contextual icon based on keywords
 * - Optional tabbed header for multi-view chart cards
 * - Optional legend toggles for showing/hiding data series
 * - Smooth fade-in animation on initial render
 * - Falls back to rendering children directly when no tabs provided
 *
 * Requirements: 5.1, 5.2, 5.3, 5.4
 */

export interface ChartTab {
  key: string;
  label: string;
  content: React.ReactNode;
}

export interface LegendToggle {
  key: string;
  label: string;
  color: string;
  enabled: boolean;
}

export interface ChartCardProps {
  title: string;
  children: React.ReactNode;
  className?: string;
  tabs?: ChartTab[];
  legendItems?: LegendToggle[];
  onLegendToggle?: (key: string) => void;
}

const iconClass = 'h-4 w-4 text-divisi-accent flex-shrink-0';

/** Pick an SVG icon based on keywords in the chart title. */
function TitleIcon({ title }: { title: string }) {
  const t = title.toLowerCase();

  // Time / trend / over time → line chart
  if (t.includes('over time') || t.includes('trend') || t.includes('monthly') || t.includes('timeline')) {
    return (
      <svg className={iconClass} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <polyline points="22 12 18 12 15 21 9 3 6 12 2 12" />
      </svg>
    );
  }

  // Currency → dollar sign
  if (t.includes('currency')) {
    return (
      <svg className={iconClass} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <line x1="12" y1="1" x2="12" y2="23" />
        <path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6" />
      </svg>
    );
  }

  // Territory / region / country / geography → globe
  if (t.includes('territory') || t.includes('territorio') || t.includes('region') || t.includes('country') || t.includes('geography')) {
    return (
      <svg className={iconClass} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <circle cx="12" cy="12" r="10" />
        <line x1="2" y1="12" x2="22" y2="12" />
        <path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z" />
      </svg>
    );
  }

  // Top / ranking / works → trophy/star
  if (t.includes('top ') || t.includes('ranking') || t.includes('best')) {
    return (
      <svg className={iconClass} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <path d="M6 9H4.5a2.5 2.5 0 0 1 0-5H6" />
        <path d="M18 9h1.5a2.5 2.5 0 0 0 0-5H18" />
        <path d="M4 22h16" />
        <path d="M10 14.66V17c0 .55-.47.98-.97 1.21C7.85 18.75 7 20.24 7 22" />
        <path d="M14 14.66V17c0 .55.47.98.97 1.21C16.15 18.75 17 20.24 17 22" />
        <path d="M18 2H6v7a6 6 0 0 0 12 0V2Z" />
      </svg>
    );
  }

  // Media / type / category / genre / source → layers/tag
  if (t.includes('media') || t.includes('type') || t.includes('category') || t.includes('genre') || t.includes('source') || t.includes('match')) {
    return (
      <svg className={iconClass} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <polygon points="12 2 2 7 12 12 22 7 12 2" />
        <polyline points="2 17 12 22 22 17" />
        <polyline points="2 12 12 17 22 12" />
      </svg>
    );
  }

  // Status / active / inactive / pending → pie/donut
  if (t.includes('status') || t.includes('active') || t.includes('inactive') || t.includes('by status')) {
    return (
      <svg className={iconClass} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <path d="M21.21 15.89A10 10 0 1 1 8 2.83" />
        <path d="M22 12A10 10 0 0 0 12 2v10z" />
      </svg>
    );
  }

  // Income / revenue / costs / amount / payable → dollar
  if (t.includes('income') || t.includes('revenue') || t.includes('cost') || t.includes('amount') || t.includes('payable') || t.includes('earning')) {
    return (
      <svg className={iconClass} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <line x1="12" y1="1" x2="12" y2="23" />
        <path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6" />
      </svg>
    );
  }

  // Entity / event / audit / log → shield/clipboard
  if (t.includes('entity') || t.includes('event') || t.includes('audit') || t.includes('log')) {
    return (
      <svg className={iconClass} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" />
      </svg>
    );
  }

  // Payee / user / composer / people → users
  if (t.includes('payee') || t.includes('composer') || t.includes('user') || t.includes('people') || t.includes('contact')) {
    return (
      <svg className={iconClass} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2" />
        <circle cx="9" cy="7" r="4" />
        <path d="M23 21v-2a4 4 0 0 0-3-3.87" />
        <path d="M16 3.13a4 4 0 0 1 0 7.75" />
      </svg>
    );
  }

  // Contract / document / statement → file
  if (t.includes('contract') || t.includes('document') || t.includes('statement')) {
    return (
      <svg className={iconClass} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
        <polyline points="14 2 14 8 20 8" />
        <line x1="16" y1="13" x2="8" y2="13" />
        <line x1="16" y1="17" x2="8" y2="17" />
      </svg>
    );
  }

  // Transaction / transfer → arrows
  if (t.includes('transaction') || t.includes('transfer')) {
    return (
      <svg className={iconClass} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <polyline points="17 1 21 5 17 9" />
        <path d="M3 11V9a4 4 0 0 1 4-4h14" />
        <polyline points="7 23 3 19 7 15" />
        <path d="M21 13v2a4 4 0 0 1-4 4H3" />
      </svg>
    );
  }

  // Suspense / pending / unmatched → alert circle
  if (t.includes('suspense') || t.includes('unmatched') || t.includes('pending')) {
    return (
      <svg className={iconClass} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <circle cx="12" cy="12" r="10" />
        <line x1="12" y1="8" x2="12" y2="12" />
        <line x1="12" y1="16" x2="12.01" y2="16" />
      </svg>
    );
  }

  // Works / music → music note
  if (t.includes('work') || t.includes('music') || t.includes('song')) {
    return (
      <svg className={iconClass} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <path d="M9 18V5l12-2v13" />
        <circle cx="6" cy="18" r="3" />
        <circle cx="18" cy="16" r="3" />
      </svg>
    );
  }

  // Default fallback → bar chart
  return (
    <svg className={iconClass} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <line x1="18" y1="20" x2="18" y2="10" />
      <line x1="12" y1="20" x2="12" y2="4" />
      <line x1="6" y1="20" x2="6" y2="14" />
    </svg>
  );
}

export default function ChartCard({
  title,
  children,
  className = '',
  tabs,
  legendItems,
  onLegendToggle,
}: ChartCardProps) {
  const [activeTabIndex, setActiveTabIndex] = useState(0);

  const hasTabs = tabs && tabs.length > 0;

  return (
    <div
      className={`
        rounded-xl border border-divisi-border
        bg-divisi-card p-4
        animate-chart-fade-in
        ${className}
      `}
    >
      {/* Header: icon + title + optional tab buttons */}
      {hasTabs ? (
        <div className="flex items-center gap-2 mb-4">
          <TitleIcon title={title} />
          <h3 className="text-sm font-medium text-divisi-text-secondary mr-4">
            {title}
          </h3>
          <div className="flex gap-1">
            {tabs.map((tab, index) => (
              <button
                key={tab.key}
                type="button"
                onClick={() => setActiveTabIndex(index)}
                className={`
                  px-3 py-1.5 text-xs font-medium rounded-md transition-colors
                  ${
                    index === activeTabIndex
                      ? 'bg-divisi-accent text-divisi-bg'
                      : 'text-divisi-text-secondary hover:text-divisi-text-primary hover:bg-white/5'
                  }
                `}
              >
                {tab.label}
              </button>
            ))}
          </div>
        </div>
      ) : (
        <div className="flex items-center gap-2 mb-4">
          <TitleIcon title={title} />
          <h3 className="text-sm font-medium text-divisi-text-secondary">
            {title}
          </h3>
        </div>
      )}

      {/* Legend items */}
      {legendItems && legendItems.length > 0 && (
        <div className="flex flex-wrap gap-3 mb-4">
          {legendItems.map((item) => (
            <button
              key={item.key}
              type="button"
              onClick={() => onLegendToggle?.(item.key)}
              className={`
                flex items-center gap-1.5 text-xs transition-opacity
                ${item.enabled ? 'opacity-100' : 'opacity-50 line-through'}
              `}
            >
              <span
                className="inline-block w-2.5 h-2.5 rounded-full"
                style={{ backgroundColor: item.color }}
              />
              <span className="text-divisi-text-secondary">{item.label}</span>
            </button>
          ))}
        </div>
      )}

      {/* Content: tabbed or direct children */}
      {hasTabs ? tabs[activeTabIndex]?.content : children}
    </div>
  );
}
