import React, { useContext, useEffect, useState } from 'react'

import {
  type Toggle,
  ToggleProviderContext,
} from '../ToggleProvider/ToggleProvider'
import Button from '../Button/Button'
import EmptyState from '../EmptyState/EmptyState'
import Tag from '../Tag/Tag'
import ToggleTable from './ToggleTable'

// Mock data for demonstration with realistic toggle examples
export const mockToggles: Toggle[] = [
  // Library toggles
  {
    application: 'Library',
    enabled: true,
    key: 'new-component-system',
    name: 'New Component System',
  },
  {
    application: 'Library',
    enabled: false,
    key: 'experimental-hooks',
    name: 'Experimental Hooks',
  },
  {
    application: 'Library',
    enabled: true,
    key: 'design-tokens-v2',
    name: 'Design Tokens V2',
  },
  // PXM toggles
  {
    application: 'PXM',
    enabled: true,
    key: 'enhanced-product-catalog',
    name: 'Enhanced Product Catalog',
  },
  {
    application: 'PXM',
    enabled: false,
    key: 'ai-product-descriptions',
    name: 'AI Product Descriptions',
  },
  {
    application: 'PXM',
    enabled: true,
    key: 'bulk-product-import',
    name: 'Bulk Product Import',
  },
  // Predict toggles
  {
    application: 'Predict',
    enabled: true,
    key: 'advanced-analytics',
    name: 'Advanced Analytics',
  },
  {
    application: 'Predict',
    enabled: false,
    key: 'machine-learning-insights',
    name: 'Machine Learning Insights',
  },
  {
    application: 'Predict',
    enabled: false,
    key: 'predictive-modeling',
    name: 'Predictive Modeling',
  },
  // Shelf toggles
  {
    application: 'Shelf',
    enabled: true,
    key: 'inventory-tracking',
    name: 'Inventory Tracking',
  },
  {
    application: 'Shelf',
    enabled: false,
    key: 'automated-restocking',
    name: 'Automated Restocking',
  },
  {
    application: 'Shelf',
    enabled: true,
    key: 'real-time-updates',
    name: 'Real-time Updates',
  },
  // Admin toggles
  {
    application: 'Admin',
    enabled: true,
    key: 'user-management-v2',
    name: 'User Management V2',
  },
  {
    application: 'Admin',
    enabled: false,
    key: 'advanced-permissions',
    name: 'Advanced Permissions',
  },
  {
    application: 'Admin',
    enabled: false,
    key: 'audit-logging',
    name: 'Audit Logging',
  },
]

// Mock implementation that simulates the CDN fetch for ToggleProvider stories
export const MockToggleProvider = ({
  children,
  distributionKey,
  environment,
  errorCallback,
  finishedLoadingCallback,
  simulateError = false,
  simulateDelay = 1000,
}: {
  children: React.ReactNode
  distributionKey: string
  environment: 'development' | 'staging' | 'production'
  errorCallback?: (error: string | Record<string, unknown>) => void
  finishedLoadingCallback?: (isLoaded: boolean) => void
  simulateError?: boolean
  simulateDelay?: number
}) => {
  const [toggles, setToggles] = useState<Toggle[] | undefined>(undefined)

  useEffect(() => {
    const timer = setTimeout(() => {
      if (simulateError) {
        const error = new Error('Failed to fetch toggles from CDN')
        errorCallback?.(error.message)
        setToggles([])
      } else {
        setToggles(mockToggles)
      }
      finishedLoadingCallback?.(true)
    }, simulateDelay)

    return () => clearTimeout(timer)
  }, [
    distributionKey,
    environment,
    simulateError,
    simulateDelay,
    errorCallback,
    finishedLoadingCallback,
  ])

  return (
    <ToggleProviderContext.Provider value={{ toggles }}>
      {children}
    </ToggleProviderContext.Provider>
  )
}

// Component that demonstrates ToggleTable functionality
export const ToggleTableDemo = ({
  title = 'ToggleTable Demo',
  showDescription = true,
}) => {
  const { toggles } = useContext(ToggleProviderContext)

  if (toggles === undefined) {
    return (
      <div className='rounded border p-4'>
        <h4>Loading Toggles...</h4>
        <p>Fetching feature toggles from CDN...</p>
      </div>
    )
  }

  if (toggles.length === 0) {
    return (
      <EmptyState
        primaryText='No Toggles Available'
        secondaryText='No feature toggles were found for this distribution key and environment.'
      />
    )
  }

  // Convert Toggle[] to the format expected by ToggleTable
  const tableData = toggles.map((toggle) => ({
    key: toggle.key,
    enabled: toggle.enabled,
    application: toggle.application, // ToggleTable uses this for grouping
  }))

  return (
    <div>
      {showDescription && (
        <div className='mb-4 rounded border bg-light-gray p-4'>
          <h4 className='mb-2'>{title}</h4>
          <p className='mb-2'>
            This demonstrates the <code>ToggleTable</code> component used in
            DevTools. Features include:
          </p>
          <ul className='mb-0 pl-4'>
            <li>Grouped by application</li>
            <li>Toggle switches to override values locally</li>
            <li>Visual indicators when local values differ from CDN</li>
          </ul>
        </div>
      )}

      <ToggleTable data={tableData} rerenderCallout={() => {}} />
    </div>
  )
}

// Simple card-based demo for comparison
export const SimpleToggleDemo = () => {
  const { toggles } = useContext(ToggleProviderContext)
  const [filter, setFilter] = useState<'all' | 'enabled' | 'disabled'>('all')

  if (toggles === undefined) {
    return (
      <div className='rounded border p-4'>
        <h4>Loading Toggles...</h4>
        <p>Fetching feature toggles from CDN...</p>
      </div>
    )
  }

  if (toggles.length === 0) {
    return (
      <EmptyState
        primaryText='No Toggles Available'
        secondaryText='No feature toggles were found for this distribution key and environment.'
      />
    )
  }

  const filteredToggles = toggles.filter((toggle) => {
    if (filter === 'enabled') return toggle.enabled
    if (filter === 'disabled') return !toggle.enabled
    return true
  })

  return (
    <div className='rounded border p-4'>
      <div className='mb-4'>
        <h4>Simple Toggle List ({toggles.length})</h4>
        <div className='mt-3'>
          <Button
            styleType={filter === 'all' ? 'primary' : 'secondary'}
            onClick={() => setFilter('all')}
            className='mr-2'
          >
            All ({toggles.length})
          </Button>
          <Button
            styleType={filter === 'enabled' ? 'primary' : 'secondary'}
            onClick={() => setFilter('enabled')}
            className='mr-2'
          >
            Enabled ({toggles.filter((t) => t.enabled).length})
          </Button>
          <Button
            styleType={filter === 'disabled' ? 'primary' : 'secondary'}
            onClick={() => setFilter('disabled')}
          >
            Disabled ({toggles.filter((t) => !t.enabled).length})
          </Button>
        </div>
      </div>

      <div className='grid gap-3'>
        {filteredToggles.map((toggle) => (
          <div key={toggle.key} className='rounded border p-3'>
            <div className='align-center mb-2 flex justify-between'>
              <h5 className='m-0'>{toggle.name}</h5>
              <Tag color={toggle.enabled ? 'green' : 'gray'}>
                {toggle.enabled ? 'Enabled' : 'Disabled'}
              </Tag>
            </div>
            <div className='color-gray text-sm'>
              <div>
                <strong>Key:</strong> {toggle.key}
              </div>
              <div>
                <strong>Application:</strong> {toggle.application}
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  )
}

// Standalone demo that doesn't require ToggleProvider context
export const StandaloneToggleTableDemo = ({
  customToggles = mockToggles,
  title = 'ToggleTable Component Demo',
  showDescription = true,
}) => {
  // Convert Toggle[] to the format expected by ToggleTable
  const tableData = customToggles.map((toggle) => ({
    key: toggle.key,
    enabled: toggle.enabled,
    application: toggle.application,
  }))

  return (
    <div>
      {showDescription && (
        <div className='mb-4 rounded border bg-light-gray p-4'>
          <h4 className='mb-2'>{title}</h4>
          <p className='mb-2'>
            The <code>ToggleTable</code> component provides a professional
            interface for managing feature toggles. This standalone demo shows
            the component without requiring a ToggleProvider.
          </p>
          <ul className='mb-0 pl-4'>
            <li>
              <strong>Application Grouping:</strong> Toggles are organized by
              application
            </li>
            <li>
              <strong>Local Overrides:</strong> Switch toggles to override
              values in localStorage
            </li>
            <li>
              <strong>Visual Indicators:</strong> Highlighted rows when local
              values differ from CDN
            </li>
            <li>
              <strong>Responsive Design:</strong> Works on desktop and mobile
              devices
            </li>
          </ul>
        </div>
      )}

      <ToggleTable data={tableData} rerenderCallout={() => {}} />
    </div>
  )
}
