import React, { createContext, useContext, useState } from 'react';
import { Card } from '../Card';

export interface TabItem {
  id: string;
  label: string;
  disabled?: boolean;
}

export interface TabsProps {
  items?: TabItem[];
  activeTab?: string;
  onTabChange?: (tabId: string) => void;
  variant?: 'default' | 'pills' | 'underline';
  size?: 'sm' | 'md' | 'lg';
  fullWidth?: boolean;
  className?: string;
  defaultValue?: string;
  value?: string;
  onValueChange?: (value: string) => void;
  children?: React.ReactNode;
}

// Context for compound component pattern
interface TabsContextType {
  activeTab: string;
  onTabChange: (tabId: string) => void;
  variant: 'default' | 'pills' | 'underline';
  size: 'sm' | 'md' | 'lg';
}

const TabsContext = createContext<TabsContextType | null>(null);

const useTabsContext = () => {
  const context = useContext(TabsContext);
  if (!context) {
    throw new Error('Tabs compound components must be used within a Tabs component');
  }
  return context;
};

const Tabs: React.FC<TabsProps> = ({
  items,
  activeTab,
  onTabChange,
  variant = 'pills',
  size = 'md',
  fullWidth = false,
  className = '',
  defaultValue,
  value,
  onValueChange,
  children
}) => {
  // Handle both controlled and uncontrolled state
  const [internalActiveTab, setInternalActiveTab] = useState(defaultValue || '');
  const currentActiveTab = value || activeTab || internalActiveTab;
  const handleTabChange = (tabId: string) => {
    if (onValueChange) {
      onValueChange(tabId);
    } else if (onTabChange) {
      onTabChange(tabId);
    } else {
      setInternalActiveTab(tabId);
    }
  };

  // If children are provided, use compound component pattern
  if (children) {
    return (
      <TabsContext.Provider value={{
        activeTab: currentActiveTab,
        onTabChange: handleTabChange,
        variant,
        size
      }}>
        <div className={className}>
          {children}
        </div>
      </TabsContext.Provider>
    );
  }
  // Size classes
  const sizeClasses = {
    sm: 'px-2 py-1.5 text-xs',
    md: 'px-3 sm:px-4 py-3 sm:py-2 text-sm',
    lg: 'px-4 sm:px-6 py-4 sm:py-3 text-base'
  };

  // Variant styles
  const getVariantClasses = (isActive: boolean, isDisabled: boolean) => {
    if (isDisabled) {
      return 'text-[var(--text-tertiary)] cursor-not-allowed opacity-50';
    }

    switch (variant) {
      case 'pills':
        return isActive
          ? 'bg-[var(--color-primary)] text-white'
          : 'text-[var(--text-secondary)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-secondary)]';

      case 'underline':
        return isActive
          ? 'text-[var(--color-primary)] border-b-2 border-[var(--color-primary)]'
          : 'text-[var(--text-secondary)] hover:text-[var(--text-primary)] border-b-2 border-transparent';

      default:
        return isActive
          ? 'bg-[var(--color-primary)] text-white'
          : 'text-[var(--text-secondary)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-secondary)]';
    }
  };

  const baseButtonClasses = `
    font-medium transition-colors
    ${fullWidth ? 'flex-1' : 'sm:flex-none'}
    ${variant === 'pills' ? 'rounded-md' : ''}
    ${sizeClasses[size]}
  `.trim();

  if (variant === 'underline') {
    return (
      <div className={`border-b border-[var(--border-primary)] ${className}`}>
        <nav className="flex">
          {items.map((item) => {
            const isActive = activeTab === item.id;
            const isDisabled = item.disabled || false;

            return (
              <button
                key={item.id}
                onClick={() => !isDisabled && onTabChange(item.id)}
                disabled={isDisabled}
                className={`
                  ${baseButtonClasses}
                  ${getVariantClasses(isActive, isDisabled)}
                `}
                type="button"
              >
                {item.label}
              </button>
            );
          })}
        </nav>
      </div>
    );
  }

  return (
    <Card className={`p-1 ${className}`}>
      <div className="flex space-x-1">
        {items.map((item) => {
          const isActive = activeTab === item.id;
          const isDisabled = item.disabled || false;

          return (
            <button
              key={item.id}
              onClick={() => !isDisabled && onTabChange(item.id)}
              disabled={isDisabled}
              className={`
                ${baseButtonClasses}
                ${getVariantClasses(isActive, isDisabled)}
              `}
              type="button"
            >
              {item.label}
            </button>
          );
        })}
      </div>
    </Card>
  );
};

// Compound Components
export interface TabsListProps {
  className?: string;
  children: React.ReactNode;
}

export const TabsList: React.FC<TabsListProps> = ({ className = '', children }) => {
  const { variant } = useTabsContext();

  const baseClasses = variant === 'underline'
    ? 'border-b border-[var(--border-primary)]'
    : 'p-1 bg-[var(--bg-secondary)] rounded-lg';

  return (
    <div className={`flex ${baseClasses} ${className}`}>
      {children}
    </div>
  );
};

export interface TabsTriggerProps {
  value: string;
  children: React.ReactNode;
  className?: string;
  disabled?: boolean;
}

export const TabsTrigger: React.FC<TabsTriggerProps> = ({
  value,
  children,
  className = '',
  disabled = false
}) => {
  const { activeTab, onTabChange, variant, size } = useTabsContext();
  const isActive = activeTab === value;

  const sizeClasses = {
    sm: 'px-2 py-1.5 text-xs',
    md: 'px-3 py-2 text-sm',
    lg: 'px-4 py-3 text-base'
  };

  const getVariantClasses = () => {
    if (disabled) {
      return 'text-[var(--text-tertiary)] cursor-not-allowed opacity-50';
    }

    switch (variant) {
      case 'pills':
        return isActive
          ? 'bg-[var(--color-primary)] text-white'
          : 'text-[var(--text-secondary)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-primary)]';

      case 'underline':
        return isActive
          ? 'text-[var(--color-primary)] border-b-2 border-[var(--color-primary)]'
          : 'text-[var(--text-secondary)] hover:text-[var(--text-primary)] border-b-2 border-transparent';

      default:
        return isActive
          ? 'bg-[var(--color-primary)] text-white'
          : 'text-[var(--text-secondary)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-secondary)]';
    }
  };

  const buttonClasses = `
    font-medium transition-colors
    ${variant === 'pills' ? 'rounded-md' : ''}
    ${sizeClasses[size]}
    ${getVariantClasses()}
    ${className}
  `.trim();

  return (
    <button
      onClick={() => !disabled && onTabChange(value)}
      disabled={disabled}
      className={buttonClasses}
      type="button"
    >
      {children}
    </button>
  );
};

export interface TabsContentProps {
  value: string;
  children: React.ReactNode;
  className?: string;
}

export const TabsContent: React.FC<TabsContentProps> = ({
  value,
  children,
  className = ''
}) => {
  const { activeTab } = useTabsContext();

  if (activeTab !== value) {
    return null;
  }

  return (
    <div className={`mt-4 ${className}`}>
      {children}
    </div>
  );
};

export default Tabs;