import React, { useEffect, useState } from 'react'
import { useComponents } from '../../contexts/ComponentContext'
import {
  FaPlus,
  FaSearch,
  FaRegEdit,
  FaTrashAlt,
  FaEye,
  FaEyeSlash,
  FaFilter,
  FaCalendarAlt,
  FaExternalLinkAlt,
  FaCog,
  FaSyncAlt,
  FaTh,
  FaList,
} from 'react-icons/fa'
import Widget from '@/components/common/Widget'
import { ROUTES_ENUM } from '@/routes/route.constant'
import { useLocalization } from '@/utils/hooks/useLocalization'
import { Loading } from '../../components/shared'
import PageTitle from '@/components/shared/PageTitle'
import { Button } from '@/components/ui'
import Dialog from '@/components/ui/Dialog'
import ComponentEditor from './ComponentEditor'
import { parseComponentDependencies } from '@/contexts/componentRuntime'
import { usePermission } from '@/utils/hooks/usePermission'
import { COMPONENT_PERMISSION } from '@/constants/permission.constant'
import Input from '@/components/ui/Input'
import Select from '@/components/ui/Select'
import type { CustomComponent } from '@/proxy/developerKit/models'
import { useStoreActions, useStoreState } from '@/store/store'
import type { ListViewLayoutType } from '../admin/listForm/edit/types'

/** Layout tercihi diger listelerle ayni yerde (admin.lists.states) saklanir. */
const VIEW_STATE_CODE = 'developerkit-components'

const ComponentManager: React.FC = () => {
  const {
    components,
    loading,
    componentErrors,
    updateComponent,
    deleteComponent,
    refreshComponents,
  } = useComponents()
  const [searchTerm, setSearchTerm] = useState('')
  const [filterActive, setFilterActive] = useState<'all' | 'active' | 'inactive'>('all')
  const [isRefreshing, setIsRefreshing] = useState(false)
  const [editorComponentId, setEditorComponentId] = useState<string | null | undefined>(undefined)
  const { states } = useStoreState((state) => state.admin.lists)
  const { setStates } = useStoreActions((a) => a.admin.lists)
  const viewMode: ListViewLayoutType =
    states.find((s) => s.listFormCode === VIEW_STATE_CODE)?.layout === 'grid' ? 'grid' : 'card'
  const setViewMode = (layout: ListViewLayoutType) =>
    setStates({ listFormCode: VIEW_STATE_CODE, layout })

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

  const filterActiveOptions = [
    { value: 'all' as const, label: translate('::App.ComponentFilter.All') },
    { value: 'active' as const, label: translate('::App.EntityFilter.Active') },
    { value: 'inactive' as const, label: translate('::App.EntityFilter.Inactive') },
  ]
  const { checkPermission } = usePermission()
  const canCreate = checkPermission(COMPONENT_PERMISSION.CREATE)
  const canUpdate = checkPermission(COMPONENT_PERMISSION.UPDATE)
  const canDelete = checkPermission(COMPONENT_PERMISSION.DELETE)

  useEffect(() => {
    void refreshComponents()
  }, [refreshComponents])

  const handleRefresh = async () => {
    setIsRefreshing(true)
    try {
      await refreshComponents()
    } finally {
      setIsRefreshing(false)
    }
  }

  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) => {
    if (window.confirm(translate('::App.DeveloperKitComponent.ConfirmDelete'))) {
      try {
        await deleteComponent(id)
      } catch (err) {
        console.error('Failed to delete component:', err)
      }
    }
  }

  const renderStatusToggle = (component: CustomComponent) => (
    <Button
      type="button"
      variant="plain"
      shape="circle"
      disabled={!canUpdate}
      className="!inline-flex !h-auto items-center gap-1 rounded !px-2 py-1 text-xs font-medium transition-colors"
      onClick={() => handleToggleActive(component.id, !component.isActive)}
    >
      {component.isActive ? (
        <>
          <FaEye className="w-4 h-4" />
          {translate('::App.Listform.ListformField.IsActive')}
        </>
      ) : (
        <>
          <FaEyeSlash className="w-4 h-4" />
          {translate('::App.Platform.Passive')}
        </>
      )}
    </Button>
  )

  const renderActions = (component: CustomComponent) => (
    <div className="flex items-center gap-1">
      {canUpdate && (
        <Button
          type="button"
          variant="solid"
          color="blue-600"
          title={translate('::App.Platform.Edit')}
          onClick={() =>
            window.open(
              ROUTES_ENUM.protected.saas.developerKit.componentsEdit.replace(':id', component.id),
              '_blank',
            )
          }
        >
          <FaRegEdit className="w-4 h-4" />
        </Button>
      )}
      <Button
        type="button"
        variant="solid"
        color="gray-600"
        disabled={!component.isActive || !component.routePath?.trim()}
        title={translate('::App.Platform.OpenUrl')}
        onClick={() => {
          const routePath = component.routePath.startsWith('/')
            ? component.routePath
            : `/${component.routePath}`
          window.open(routePath, '_blank')
        }}
      >
        <FaExternalLinkAlt className="w-4 h-4" />
      </Button>
      <Button
        type="button"
        variant="solid"
        color="green-600"
        title={translate('::App.Platform.View')}
        onClick={() => setEditorComponentId(component.id)}
      >
        <FaCog className="w-4 h-4" />
      </Button>
      {canDelete && (
        <Button
          type="button"
          variant="solid"
          color="red-600"
          title={translate('::App.Platform.Delete')}
          onClick={() => handleDelete(component.id)}
        >
          <FaTrashAlt className="w-4 h-4" />
        </Button>
      )}
    </div>
  )

  return (
    <div className="space-y-4">
      <PageTitle title={translate('::' + 'App.DeveloperKit.Components')} />

      <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mt-2 mb-4">
        <Widget
          title={translate('::App.DeveloperKitComponent.Total')}
          value={totalComponents}
          color="purple"
          icon="FaPuzzlePiece"
          valueClassName="text-3xl"
          subTitle={translate('::App.DeveloperKitComponent.TotalDescription')}
        />
        <Widget
          title={translate('::App.DeveloperKitComponent.Active')}
          value={activeComponents}
          color="green"
          icon="FaCheckCircle"
          valueClassName="text-3xl"
          subTitle={translate('::App.DeveloperKitComponent.ActiveDescription')}
        />
        <Widget
          title={translate('::App.DeveloperKitComponent.Inactive')}
          value={inactiveComponents}
          color="gray"
          icon="FaTimesCircle"
          valueClassName="text-3xl"
          subTitle={translate('::App.DeveloperKitComponent.InactiveDescription')}
        />
      </div>

      {/* Filters */}
      <div className="flex flex-col sm:flex-row gap-3">
        <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
            unstyle
            type="text"
            placeholder={translate('::App.DeveloperKitComponent.SearchPlaceholder')}
            value={searchTerm}
            className="w-full pl-10 pr-2 py-1 border border-slate-300 dark:border-gray-700 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            onChange={(e) => setSearchTerm(e.target.value)}
          />
        </div>
        <div className="flex items-center gap-2">
          <FaFilter className="w-5 h-5 text-slate-500 dark:text-gray-400" />
          <Select
            size="sm"
            className="min-w-[9rem]"
            options={filterActiveOptions}
            value={filterActiveOptions.filter((o) => o.value === filterActive)}
            onChange={(option) => setFilterActive(option?.value ?? 'all')}
          />
        </div>
        <Button
          className="flex items-center gap-2"
          disabled={loading || isRefreshing}
          type="button"
          variant="default"
          onClick={() => void handleRefresh()}
        >
          <FaSyncAlt className={isRefreshing ? 'animate-spin' : ''} />
          {translate('::App.Platform.Refresh')}
        </Button>
        {canCreate && (
          <div>
            <Button
              type="button"
              variant="solid"
              className="flex items-center gap-2"
              onClick={() => setEditorComponentId(null)}
            >
              <FaPlus className="w-4 h-4" />
              {translate('::App.DeveloperKitComponent.New')}
            </Button>
          </div>
        )}
        <div className="flex items-center gap-1">
          <Button
            type="button"
            icon={<FaTh />}
            variant={viewMode === 'card' ? 'solid' : 'default'}
            title={translate('::App.Platform.CardView')}
            onClick={() => setViewMode('card')}
          />
          <Button
            type="button"
            icon={<FaList />}
            variant={viewMode === 'grid' ? 'solid' : 'default'}
            title={translate('::App.Platform.ListView')}
            onClick={() => setViewMode('grid')}
          />
        </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 ? (
        viewMode === 'card' ? (
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-4 gap-4">
            {filteredComponents.map((component) => (
              <div
                key={component.id}
                className="bg-white dark:bg-gray-900 rounded-lg border border-slate-200 dark:border-gray-700 shadow-sm hover:shadow-md transition-shadow"
              >
                <div className="p-4">
                  <div className="flex items-start justify-between">
                    {/* Sol taraf */}
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2 mb-1">
                        <h3
                          className="text-base font-semibold text-slate-900 dark:text-gray-100 truncate"
                          title={component.name}
                        >
                          {component.name}
                        </h3>
                        <div
                          className={`w-2 h-2 shrink-0 rounded-full ${
                            component.isActive ? 'bg-green-500' : 'bg-slate-300 dark:bg-gray-700'
                          }`}
                        />
                      </div>

                      <p className="text-slate-600 dark:text-gray-300 text-sm mb-2 truncate">
                        {parseComponentDependencies(component.dependencies).join(', ') ||
                          translate('::App.DeveloperKitComponent.NoDependencies')}
                      </p>

                      <p
                        className="text-slate-600 dark:text-gray-300 text-sm mb-2 truncate"
                        title={component.routePath}
                      >
                        {component.routePath}
                      </p>

                      {component.description && (
                        <p className="text-slate-600 dark:text-gray-300 text-sm mb-2 line-clamp-2">
                          {component.description}
                        </p>
                      )}

                      {componentErrors[component.name] && (
                        <p
                          className="text-xs text-red-700 dark:text-red-300 bg-red-50 dark:bg-red-950 border border-red-200 dark:border-red-800 rounded px-2 py-1 mb-2 break-words"
                          title={componentErrors[component.name]}
                        >
                          {componentErrors[component.name]}
                        </p>
                      )}
                    </div>

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

                  {/* Actions */}
                  <div className="flex items-center justify-between gap-1 pt-2 border-t border-slate-100 dark:border-gray-700">
                    {renderStatusToggle(component)}
                    {renderActions(component)}
                  </div>
                </div>
              </div>
            ))}
          </div>
        ) : (
          <div className="bg-white dark:bg-gray-900 rounded-lg border border-slate-200 dark:border-gray-700 shadow-sm overflow-x-auto">
            <table className="w-full text-sm">
              <thead className="bg-slate-50 dark:bg-gray-800 text-slate-600 dark:text-gray-300">
                <tr>
                  <th className="text-left font-medium px-4 py-2">
                    {translate('::App.Platform.Name')}
                  </th>
                  <th className="text-left font-medium px-4 py-2">
                    {translate('::App.Platform.Dependencies')}
                  </th>
                  <th className="text-left font-medium px-4 py-2">
                    {translate('::App.Platform.RoutePath')}
                  </th>
                  <th className="text-left font-medium px-4 py-2">
                    {translate('::App.Platform.Description')}
                  </th>
                  <th className="text-left font-medium px-4 py-2 whitespace-nowrap">
                    {translate('::App.Platform.Modified')}
                  </th>
                  <th className="text-left font-medium px-4 py-2">
                    {translate('::App.Platform.Status')}
                  </th>
                  <th className="text-right font-medium px-4 py-2">
                    {translate('::App.Platform.Actions')}
                  </th>
                </tr>
              </thead>
              <tbody>
                {filteredComponents.map((component) => (
                  <tr
                    key={component.id}
                    className="border-t border-slate-100 dark:border-gray-700 hover:bg-slate-50 dark:hover:bg-gray-800"
                  >
                    <td className="px-4 py-2">
                      <div className="flex items-center gap-2">
                        <div
                          className={`w-2 h-2 shrink-0 rounded-full ${
                            component.isActive ? 'bg-green-500' : 'bg-slate-300 dark:bg-gray-700'
                          }`}
                        />
                        <span className="font-medium text-slate-900 dark:text-gray-100">
                          {component.name}
                        </span>
                      </div>
                      {componentErrors[component.name] && (
                        <p
                          className="mt-1 text-xs text-red-700 dark:text-red-300 break-words"
                          title={componentErrors[component.name]}
                        >
                          {componentErrors[component.name]}
                        </p>
                      )}
                    </td>
                    <td className="px-4 py-2 text-slate-600 dark:text-gray-300">
                      {parseComponentDependencies(component.dependencies).join(', ') ||
                        translate('::App.DeveloperKitComponent.NoDependencies')}
                    </td>
                    <td className="px-4 py-2 text-slate-600 dark:text-gray-300">
                      {component.routePath}
                    </td>
                    <td className="px-4 py-2 text-slate-600 dark:text-gray-300">
                      {component.description}
                    </td>
                    <td className="px-4 py-2 text-slate-500 dark:text-gray-400 whitespace-nowrap">
                      {component.lastModificationTime
                        ? new Date(component.lastModificationTime).toLocaleDateString()
                        : ''}
                    </td>
                    <td className="px-4 py-2">{renderStatusToggle(component)}</td>
                    <td className="px-4 py-2">
                      <div className="flex justify-end">{renderActions(component)}</div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </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.EmptyFiltered.FilteredTitle')
                : translate('::App.EmptyInitial.InitialTitle')}
            </h3>
            <p className="text-slate-600 mb-6">
              {searchTerm || filterActive !== 'all'
                ? translate('::App.DeveloperKit.EmptyFilteredDescription')
                : translate('::App.EmptyInitial.InitialDescription')}
            </p>
            {canCreate && !searchTerm && filterActive === 'all' && (
              <button
                type="button"
                className="inline-flex items-center gap-2 bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors"
                onClick={() => setEditorComponentId(null)}
              >
                <FaPlus className="w-4 h-4" />
                {translate('::App.ComponentEditorTitle.Create')}
              </button>
            )}
          </div>
        </div>
      )}

      <Dialog
        isOpen={editorComponentId !== undefined}
        width={720}
        height="85vh"
        contentClassName="overflow-y-auto"
        onClose={() => setEditorComponentId(undefined)}
        onRequestClose={() => setEditorComponentId(undefined)}
      >
        <ComponentEditor
          key={editorComponentId ?? 'new'}
          componentId={editorComponentId}
          onClose={() => setEditorComponentId(undefined)}
          onSaved={refreshComponents}
        />
      </Dialog>
    </div>
  )
}

export default ComponentManager
