import React, { useState } from 'react'
import { Link } from 'react-router-dom'
import { useComponents } from '../../contexts/ComponentContext'
import {
  FaPlus,
  FaSearch,
  FaRegEdit,
  FaTrashAlt,
  FaEye,
  FaEyeSlash,
  FaFilter,
  FaCalendarAlt,
  FaPuzzlePiece,
  FaCheckCircle,
  FaTimesCircle,
} from 'react-icons/fa'
import { ROUTES_ENUM } from '@/routes/route.constant'
import { useLocalization } from '@/utils/hooks/useLocalization'
import { Loading } from '../../components/shared'
import { APP_NAME } from '@/constants/app.constant'
import { Helmet } from 'react-helmet'

const ComponentManager: React.FC = () => {
  const { components, loading, updateComponent, deleteComponent } = useComponents()
  const [searchTerm, setSearchTerm] = useState('')
  const [filterActive, setFilterActive] = useState<'all' | 'active' | 'inactive'>('all')

  // Calculate statistics
  const totalComponents = components?.length || 0
  const activeComponents = components?.filter((c) => c.isActive).length || 0
  const inactiveComponents = totalComponents - activeComponents
  const { translate } = useLocalization()

  const stats = [
    {
      name: translate('::App.DeveloperKit.Component.Total'),
      value: totalComponents,
      icon: FaPuzzlePiece,
      color: 'text-purple-600',
      bgColor: 'bg-purple-100',
    },
    {
      name: translate('::App.DeveloperKit.Component.Active'),
      value: activeComponents,
      icon: FaCheckCircle,
      color: 'text-emerald-600',
      bgColor: 'bg-emerald-100',
    },
    {
      name: translate('::App.DeveloperKit.Component.Inactive'),
      value: inactiveComponents,
      icon: FaTimesCircle,
      color: 'text-slate-600',
      bgColor: 'bg-slate-100',
    },
  ]

  const filteredComponents = components?.filter((component) => {
    const matchesSearch =
      component.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      (component.description || '').toLowerCase().includes(searchTerm.toLowerCase())

    const matchesFilter =
      filterActive === 'all' ||
      (filterActive === 'active' && component.isActive) ||
      (filterActive === 'inactive' && !component.isActive)

    return matchesSearch && matchesFilter
  })

  const handleToggleActive = async (id: string, isActive: boolean) => {
    try {
      const component = components?.find((c) => c.id === id)
      if (component) {
        await updateComponent(id, { ...component, isActive })
      }
    } catch (err) {
      console.error('Failed to toggle component status:', err)
    }
  }

  const handleDelete = async (id: string, name: string) => {
    if (window.confirm(translate('::App.DeveloperKit.Component.ConfirmDelete'))) {
      try {
        await deleteComponent(id)
      } catch (err) {
        console.error('Failed to delete component:', err)
      }
    }
  }

  return (
    <div className="space-y-4">
      <Helmet
        titleTemplate={`%s | ${APP_NAME}`}
        title={translate('::' + 'App.DeveloperKit.Components')}
        defaultTitle={APP_NAME}
      ></Helmet>

      <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mt-2 mb-4">
        {stats.map((stat, index) => (
          <div key={index} className="bg-white rounded-lg border border-slate-200 p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-slate-600 mb-1">{stat.name}</p>
                <p className="text-3xl font-bold text-slate-900">{stat.value}</p>
              </div>
              <div className={`p-3 rounded-lg ${stat.bgColor}`}>
                <stat.icon className={`w-6 h-6 ${stat.color}`} />
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* Filters */}
      <div className="flex flex-col sm:flex-row gap-4">
        <div className="flex-1 relative">
          <FaSearch className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-slate-400" />
          <input
            type="text"
            placeholder={translate('::App.DeveloperKit.Component.SearchPlaceholder')}
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="w-full pl-10 pr-4 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
          />
        </div>
        <div className="flex items-center gap-2">
          <FaFilter className="w-5 h-5 text-slate-500" />
          <select
            value={filterActive}
            onChange={(e) => setFilterActive(e.target.value as 'all' | 'active' | 'inactive')}
            className="px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
          >
            <option value="all">{translate('::App.DeveloperKit.Component.Filter.All')}</option>
            <option value="active">
              {translate('::App.DeveloperKit.Component.Filter.Active')}
            </option>
            <option value="inactive">
              {translate('::App.DeveloperKit.Component.Filter.Inactive')}
            </option>
          </select>
        </div>
        <div>
          <Link
            to={ROUTES_ENUM.protected.saas.developerKit.componentsNew}
            className="flex items-center gap-2 bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors"
          >
            <FaPlus className="w-4 h-4" />
            {translate('::App.DeveloperKit.Component.New')}
          </Link>
        </div>
      </div>

      {/* Components List */}
      {loading ? (
        <div className="flex items-center justify-center min-h-screen bg-gray-50">
          <div className="text-center">
            <Loading loading={loading} />
          </div>
        </div>
      ) : filteredComponents?.length > 0 ? (
        <div className="grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-4 gap-6">
          {filteredComponents.map((component) => (
            <div
              key={component.id}
              className="bg-white rounded-lg border border-slate-200 shadow-sm hover:shadow-md transition-shadow"
            >
              <div className="p-6">
                <div className="flex items-start justify-between">
                  {/* Sol taraf */}
                  <div className="flex-1">
                    <div className="flex items-center gap-2 mb-1">
                      <h3 className="text-lg font-semibold text-slate-900">{component.name}</h3>
                      <div
                        className={`w-2 h-2 rounded-full ${
                          component.isActive ? 'bg-green-500' : 'bg-slate-300'
                        }`}
                      />
                    </div>

                    <p className="text-slate-600 text-sm mb-3">
                      {(() => {
                        try {
                          const parsed = JSON.parse(component.dependencies ?? '[]')
                          return Array.isArray(parsed) && parsed.length > 0
                            ? `${parsed.join(', ')}`
                            : translate('::App.DeveloperKit.Component.NoDependencies')
                        } catch {
                          return translate('::App.DeveloperKit.Component.NoDependencies')
                        }
                      })()}
                    </p>

                    {component.description && (
                      <p className="text-slate-600 text-sm mb-3">{component.description}</p>
                    )}
                  </div>

                  {/* Sağ taraf */}
                  {component.lastModificationTime && (
                    <div className="flex items-center gap-1 text-xs text-slate-500 ml-4 whitespace-nowrap">
                      <FaCalendarAlt className="w-3 h-3" />
                      <span>
                        {new Date(component.lastModificationTime).toLocaleDateString() ?? ''}
                      </span>
                    </div>
                  )}
                </div>

                {/* Props Preview */}
                {component.props && (
                  <div className="mb-4">
                    <p className="text-xs font-medium text-slate-700 mb-1">
                      {translate('::App.DeveloperKit.Component.PropsLabel')}
                    </p>
                    <code className="text-xs bg-slate-100 text-slate-600 px-2 py-1 rounded">
                      {component.props}
                    </code>
                  </div>
                )}

                {/* Actions */}
                <div className="flex items-center justify-between pt-2 border-t border-slate-100">
                  <div className="flex items-center gap-2">
                    <button
                      onClick={() => handleToggleActive(component.id, !component.isActive)}
                      className={`flex items-center gap-1 px-2 py-1 rounded text-xs font-medium transition-colors ${
                        component.isActive
                          ? 'bg-green-100 text-green-700 hover:bg-green-200'
                          : 'bg-slate-100 text-slate-600 hover:bg-slate-200'
                      }`}
                    >
                      {component.isActive ? (
                        <>
                          <FaEye className="w-3 h-3" />
                          {translate('::App.DeveloperKit.Component.Active')}
                        </>
                      ) : (
                        <>
                          <FaEyeSlash className="w-3 h-3" />
                          {translate('::App.DeveloperKit.Component.Inactive')}
                        </>
                      )}
                    </button>
                  </div>
                  <div className="flex items-center gap-1">
                    <Link
                      to={ROUTES_ENUM.protected.saas.developerKit.componentsEdit.replace(
                        ':id',
                        component.id,
                      )}
                      target="_blank"
                      className="p-2 text-slate-600 hover:text-blue-600 hover:bg-blue-50 rounded transition-colors"
                      title={translate('::App.DeveloperKit.Component.Edit')}
                    >
                      <FaRegEdit className="w-4 h-4" />
                    </Link>
                    <Link
                      to={ROUTES_ENUM.protected.saas.developerKit.componentsView.replace(
                        ':id',
                        component.id,
                      )}
                      className="p-2 text-slate-600 hover:text-blue-600 hover:bg-blue-50 rounded transition-colors"
                      title={translate('::App.DeveloperKit.Component.View')}
                    >
                      <FaEye className="w-4 h-4" />
                    </Link>
                    <button
                      onClick={() => handleDelete(component.id, component.name)}
                      className="p-2 text-slate-600 hover:text-red-600 hover:bg-red-50 rounded transition-colors"
                      title={translate('::App.DeveloperKit.Component.Delete')}
                    >
                      <FaTrashAlt className="w-4 h-4" />
                    </button>
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>
      ) : (
        <div className="text-center py-12">
          <div className="mx-auto">
            <div className="bg-slate-100 rounded-full w-16 h-16 flex items-center justify-center mx-auto mb-4">
              <FaPlus className="w-8 h-8 text-slate-500" />
            </div>
            <h3 className="text-lg font-medium text-slate-900 mb-2">
              {searchTerm || filterActive !== 'all'
                ? translate('::App.DeveloperKit.Component.Empty.Filtered.Title')
                : translate('::App.DeveloperKit.Component.Empty.Initial.Title')}
            </h3>
            <p className="text-slate-600 mb-6">
              {searchTerm || filterActive !== 'all'
                ? translate('::App.DeveloperKit.EmptyFilteredDescription')
                : translate('::App.DeveloperKit.Component.Empty.Initial.Description')}
            </p>
            {!searchTerm && filterActive === 'all' && (
              <Link
                to={ROUTES_ENUM.protected.saas.developerKit.componentsNew}
                className="inline-flex items-center gap-2 bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors"
              >
                <FaPlus className="w-4 h-4" />
                {translate('::App.DeveloperKit.Component.Empty.Initial.Action')}
              </Link>
            )}
          </div>
        </div>
      )}
    </div>
  )
}

export default ComponentManager
