import React, { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useEntities } from '../../contexts/EntityContext'
import {
  FaBolt,
  FaSearch,
  FaFilter,
  FaCalendarAlt,
  FaDatabase,
  FaPlay,
  FaCheckCircle,
  FaRegBell,
  FaRegClock,
  FaRegFileAlt,
  FaDownload,
  FaEye,
  FaSync,
  FaTrashAlt,
  FaPlus,
} from 'react-icons/fa'
import { ROUTES_ENUM } from '@/routes/route.constant'
import { useLocalization } from '@/utils/hooks/useLocalization'

const MigrationManager: React.FC = () => {
  const navigate = useNavigate()
  const {
    entities,
    migrations,
    generateMigration,
    applyMigration,
    deleteMigration,
    generateCrudEndpoints,
    loading,
    error,
  } = useEntities()
  const [searchTerm, setSearchTerm] = useState('')
  const [filterStatus, setFilterStatus] = useState<'all' | 'pending' | 'applied' | 'failed'>('all')
  const [selectedMigration, setSelectedMigration] = useState<string | null>(null)
  const [applyingMigration, setApplyingMigration] = useState<string | null>(null)
  const [deletingMigration, setDeletingMigration] = useState<string | null>(null)
  const [generatingEndpoints, setGeneratingEndpoints] = useState<string | null>(null)
  const { translate } = useLocalization()

  const filteredMigrations = migrations.filter((migration) => {
    const matchesSearch =
      migration.entityName.toLowerCase().includes(searchTerm.toLowerCase()) ||
      (migration.fileName && migration.fileName.toLowerCase().includes(searchTerm.toLowerCase()))

    const matchesStatusFilter = filterStatus === 'all' || migration.status === filterStatus

    return matchesSearch && matchesStatusFilter
  })

  const handleGenerateMigration = async (entityId: string) => {
    try {
      await generateMigration(entityId)
    } catch (error) {
      console.error('Failed to generate migration:', error)
    }
  }

  const handleApplyMigration = async (migrationId: string) => {
    try {
      setApplyingMigration(migrationId)
      await applyMigration(migrationId)
    } catch (error) {
      console.error('Failed to apply migration:', error)
    } finally {
      setApplyingMigration(null)
    }
  }

  const handleDeleteMigration = async (migrationId: string) => {
    try {
      setDeletingMigration(migrationId)
      await deleteMigration(migrationId)
    } catch (error) {
      console.error('Failed to delete migration:', error)
    } finally {
      setDeletingMigration(null)
    }
  }

  const handleDownloadMigration = (migration: (typeof migrations)[0]) => {
    if (!migration.sqlScript) return

    const blob = new Blob([migration.sqlScript], { type: 'text/sql' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download =
      migration.fileName ||
      `migration_${migration.entityName}_${new Date().toISOString().split('T')[0]}.sql`
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    URL.revokeObjectURL(url)
  }

  const handleGenerateCrudEndpoints = async (entityId: string) => {
    try {
      setGeneratingEndpoints(entityId)
      await generateCrudEndpoints(entityId)
      // Navigate to API Endpoints page after successful generation
      navigate(ROUTES_ENUM.protected.saas.developerKit.migrations)
    } catch (error) {
      console.error('Failed to generate CRUD endpoints:', error)
    } finally {
      setGeneratingEndpoints(null)
    }
  }

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'pending':
        return 'bg-yellow-100 text-yellow-800 border-yellow-200'
      case 'applied':
        return 'bg-green-100 text-green-800 border-green-200'
      case 'failed':
        return 'bg-red-100 text-red-800 border-red-200'
      default:
        return 'bg-slate-100 text-slate-800 border-slate-200'
    }
  }

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'pending':
        return FaRegClock
      case 'applied':
        return FaCheckCircle
      case 'failed':
        return FaRegBell
      default:
        return FaRegClock
    }
  }

  const stats = {
    total: migrations.length,
    pending: migrations.filter((m) => m.status === 'pending').length,
    applied: migrations.filter((m) => m.status === 'applied').length,
    failed: migrations.filter((m) => m.status === 'failed').length,
  }

  const entitiesNeedingMigration = entities.filter(
    (e) => e.migrationStatus === 'pending' || !e.migrationId,
  )

  return (
    <div className="space-y-4">
      {/* Error Message */}
      {error && (
        <div className="mb-6 bg-red-50 border border-red-200 rounded-lg p-4">
          <div className="flex items-center gap-2 text-red-800">
            <FaRegBell className="w-5 h-5" />
            <span className="font-medium">Error</span>
          </div>
          <p className="text-red-700 text-sm mt-1">{error}</p>
        </div>
      )}

      <div className="flex items-center justify-between mb-4">
        <div>
          <h1 className="text-2xl font-bold text-slate-900">
            {translate('::App.DeveloperKit.Migrations')}
          </h1>
          <p className="text-slate-600">{translate('::App.DeveloperKit.Migration.Description')}</p>
        </div>
        <div className="flex items-center gap-3">
          <div className="flex items-center gap-2 bg-blue-100 text-blue-700 px-3 py-1 rounded-full text-sm font-medium">
            <FaDatabase className="w-4 h-4" />
            {translate('::App.DeveloperKit.Migration.SchemaManagement')}
          </div>
          {loading && (
            <div className="flex items-center gap-2 bg-yellow-100 text-yellow-700 px-3 py-1 rounded-full text-sm font-medium">
              <FaSync className="w-4 h-4 animate-spin" />
              {translate('::App.DeveloperKit.Migration.Loading')}
            </div>
          )}
        </div>
      </div>

      {/* Stats Cards */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-4">
        <div className="bg-white rounded-xl shadow-sm border border-slate-200 p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-slate-600">
                {translate('::App.DeveloperKit.Migration.Total')}
              </p>
              <p className="text-2xl font-bold text-slate-900 mt-1">{stats.total}</p>
            </div>
            <div className="bg-blue-100 text-blue-600 p-3 rounded-lg">
              <FaRegFileAlt className="w-6 h-6" />
            </div>
          </div>
        </div>
        <div className="bg-white rounded-xl shadow-sm border border-slate-200 p-4">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-slate-600">
                {translate('::App.DeveloperKit.Migration.Pending')}
              </p>
              <p className="text-2xl font-bold text-slate-900 mt-1">{stats.pending}</p>
            </div>
            <div className="bg-yellow-100 text-yellow-600 p-3 rounded-lg">
              <FaRegClock className="w-6 h-6" />
            </div>
          </div>
        </div>
        <div className="bg-white rounded-xl shadow-sm border border-slate-200 p-4">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-slate-600">
                {translate('::App.DeveloperKit.Migration.Applied')}
              </p>
              <p className="text-2xl font-bold text-slate-900 mt-1">{stats.applied}</p>
            </div>
            <div className="bg-green-100 text-green-600 p-3 rounded-lg">
              <FaCheckCircle className="w-6 h-6" />
            </div>
          </div>
        </div>
        <div className="bg-white rounded-xl shadow-sm border border-slate-200 p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-slate-600">
                {translate('::App.DeveloperKit.Migration.Failed')}
              </p>
              <p className="text-2xl font-bold text-slate-900 mt-1">{stats.failed}</p>
            </div>
            <div className="bg-red-100 text-red-600 p-3 rounded-lg">
              <FaRegBell className="w-6 h-6" />
            </div>
          </div>
        </div>
      </div>

      {/* Entities Needing Migration */}
      {entitiesNeedingMigration.length > 0 && (
        <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4 mb-4">
          <div className="flex items-start gap-4">
            <div className="bg-yellow-100 rounded-lg p-2">
              <FaBolt className="w-6 h-6 text-yellow-600" />
            </div>
            <div className="flex-1">
              <h3 className="text-lg font-semibold text-slate-900">
                {translate('::App.DeveloperKit.Migration.EntitiesRequireMigration')}
              </h3>
              <p className="text-slate-700 mb-2">
                {translate('::App.DeveloperKit.Migration.EntitiesRequireMigrationDescription')}
              </p>
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-6 gap-3">
                {entitiesNeedingMigration.map((entity) => (
                  <div key={entity.id} className="bg-white border border-yellow-300 rounded-lg p-4">
                    <div className="flex items-center justify-between">
                      <div>
                        <h4 className="font-medium text-slate-900">{entity.displayName}</h4>
                        <p className="text-sm text-slate-600">
                          {entity.fields.length} {translate('::App.DeveloperKit.Migration.Fields')}
                        </p>
                      </div>
                      <button
                        onClick={() => handleGenerateMigration(entity.id)}
                        disabled={loading}
                        className="bg-yellow-600 text-white px-3 py-1 rounded text-sm hover:bg-yellow-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                      >
                        {loading
                          ? translate('::App.DeveloperKit.Migration.Generating')
                          : translate('::App.DeveloperKit.Migration.Generate')}
                      </button>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Filters */}
      <div className="flex flex-col lg: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.Migration.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 transition-colors"
          />
        </div>
        <div className="flex items-center gap-4">
          <div className="flex items-center gap-2">
            <FaFilter className="w-5 h-5 text-slate-500" />
            <select
              value={filterStatus}
              onChange={(e) =>
                setFilterStatus(e.target.value as 'all' | 'pending' | 'applied' | 'failed')
              }
              className="px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-colors"
            >
              <option value="all">{translate('::App.DeveloperKit.Migration.AllStatus')}</option>
              <option value="pending">Pending</option>
              <option value="applied">Applied</option>
              <option value="failed">Failed</option>
            </select>
          </div>
        </div>
      </div>

      {/* Migrations List */}
      {filteredMigrations.length > 0 ? (
        <div className="grid grid-cols-1 xl:grid-cols-3 gap-6">
          {filteredMigrations.map((migration) => {
            const StatusIcon = getStatusIcon(migration.status)
            return (
              <div
                key={migration.id}
                className="bg-white rounded-lg border border-slate-200 shadow-sm"
              >
                <div className="p-6">
                  <div className="flex items-start justify-between mb-4">
                    {/* Sol taraf */}
                    <div className="flex items-center gap-3">
                      <div className="bg-blue-100 text-blue-600 p-2 rounded-lg">
                        <FaDatabase className="w-5 h-5" />
                      </div>
                      <div>
                        <h3 className="text-lg font-semibold text-slate-900">
                          {migration.fileName || `Migration for ${migration.entityName}`}
                        </h3>
                        <p className="text-sm text-slate-600">Entity: {migration.entityName}</p>
                      </div>
                    </div>

                    {/* Sağ taraf */}
                    <div className="flex flex-col items-end gap-2 text-right">
                      {/* Status etiketi */}
                      <span
                        className={`px-3 py-1 text-sm font-medium rounded-full border ${getStatusColor(
                          migration.status,
                        )}`}
                      >
                        <StatusIcon className="w-4 h-4 inline mr-1" />
                        {migration.status.charAt(0).toUpperCase() + migration.status.slice(1)}
                      </span>

                      {/* Tarihler */}
                      <div className="flex flex-col items-end text-xs text-slate-500">
                        <div className="flex items-center gap-1">
                          <FaCalendarAlt className="w-3 h-3" />
                          <span>
                            {translate('::App.DeveloperKit.Migration.Created')}{' '}
                            {new Date(migration.creationTime).toLocaleDateString()}
                          </span>
                        </div>
                        {migration.appliedAt && (
                          <div className="flex items-center gap-1">
                            <FaCheckCircle className="w-3 h-3" />
                            <span>
                              {translate('::App.DeveloperKit.Migration.AppliedLabel')}{' '}
                              {new Date(migration.appliedAt).toLocaleDateString()}
                            </span>
                          </div>
                        )}
                      </div>
                    </div>
                  </div>

                  {/* Actions */}
                  <div className="flex items-center justify-between pt-4 border-t border-slate-100">
                    <div className="flex items-center gap-2">
                      <button
                        onClick={() =>
                          setSelectedMigration(
                            selectedMigration === migration.id ? null : migration.id,
                          )
                        }
                        className={`flex items-center gap-1 px-3 py-1 text-sm rounded transition-colors ${
                          migration.sqlScript
                            ? 'text-slate-600 hover:text-slate-900 hover:bg-slate-100'
                            : 'text-orange-600 hover:text-orange-900 hover:bg-orange-50'
                        }`}
                      >
                        <FaEye className="w-4 h-4" />
                        {translate('::App.DeveloperKit.Migration.ViewSQL')}
                        {!migration.sqlScript && (
                          <span className="ml-1 text-xs text-orange-500">
                            ({translate('::App.DeveloperKit.Migration.NoSQL')})
                          </span>
                        )}
                      </button>
                      <button
                        onClick={() => handleDownloadMigration(migration)}
                        disabled={!migration.sqlScript}
                        className={`flex items-center gap-1 px-3 py-1 text-sm rounded transition-colors ${
                          migration.sqlScript
                            ? 'text-slate-600 hover:text-slate-900 hover:bg-slate-100'
                            : 'text-slate-400 cursor-not-allowed'
                        }`}
                      >
                        <FaDownload className="w-4 h-4" />
                        {translate('::App.DeveloperKit.Migration.Download')}
                      </button>
                    </div>
                    <div className="flex items-center gap-2">
                      {migration.status === 'pending' && (
                        <>
                          <button
                            onClick={() => handleApplyMigration(migration.id)}
                            disabled={applyingMigration === migration.id || loading}
                            className="flex items-center gap-2 bg-green-600 text-white px-4 py-2 rounded-lg hover:bg-green-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                          >
                            {applyingMigration === migration.id ? (
                              <>
                                <FaSync className="w-4 h-4 animate-spin" />
                                {translate('::App.DeveloperKit.Migration.Applying')}
                              </>
                            ) : (
                              <>
                                <FaPlay className="w-4 h-4" />
                                {translate('::App.DeveloperKit.Migration.ApplyMigration')}
                              </>
                            )}
                          </button>
                          <button
                            onClick={() => handleDeleteMigration(migration.id)}
                            disabled={deletingMigration === migration.id || loading}
                            className="flex items-center gap-2 bg-red-600 text-white px-3 py-2 rounded-lg hover:bg-red-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                          >
                            {deletingMigration === migration.id ? (
                              <FaSync className="w-4 h-4 animate-spin" />
                            ) : (
                              <FaTrashAlt className="w-4 h-4" />
                            )}
                          </button>
                        </>
                      )}
                      {migration.status === 'applied' && (
                        <button
                          onClick={() => handleGenerateCrudEndpoints(migration.entityId)}
                          disabled={generatingEndpoints === migration.entityId || loading}
                          className="flex items-center gap-2 bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                        >
                          {generatingEndpoints === migration.entityId ? (
                            <>
                              <FaSync className="w-4 h-4 animate-spin" />
                              {translate('::App.DeveloperKit.Migration.Generating')}
                            </>
                          ) : (
                            <>
                              <FaPlus className="w-4 h-4" />
                              {translate('::App.DeveloperKit.Migration.GenerateCrudEndpoints')}
                            </>
                          )}
                        </button>
                      )}
                    </div>
                  </div>

                  {/* SQL Script Preview */}
                  {selectedMigration === migration.id && (
                    <div className="mt-4 pt-4 border-t border-slate-200">
                      <h4 className="font-medium text-slate-900 mb-2">
                        {translate('::App.DeveloperKit.Migration.SQLScriptLabel')}
                      </h4>
                      {migration.sqlScript ? (
                        <div className="bg-slate-900 rounded-lg p-4 overflow-x-auto">
                          <pre className="text-green-400 text-sm">
                            <code>{migration.sqlScript}</code>
                          </pre>
                        </div>
                      ) : (
                        <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
                          <div className="flex items-center gap-2 text-yellow-800">
                            <FaRegBell className="w-5 h-5" />
                            <span className="font-medium">
                              {translate('::App.DeveloperKit.Migration.NoSQLScript')}
                            </span>
                          </div>
                          <p className="text-yellow-700 text-sm mt-1">
                            {translate('::App.DeveloperKit.Migration.NoSQLScriptDesc')}
                          </p>
                        </div>
                      )}
                    </div>
                  )}

                  {/* Error Message */}
                  {migration.status === 'failed' && migration.errorMessage && (
                    <div className="mt-4 pt-4 border-t border-slate-200">
                      <div className="bg-red-50 border border-red-200 rounded-lg p-4">
                        <div className="flex items-center gap-2 text-red-800 mb-2">
                          <FaRegBell className="w-5 h-5" />
                          <span className="font-medium">
                            {translate('::App.DeveloperKit.Migration.MigrationFailed')}
                          </span>
                        </div>
                        <p className="text-red-700 text-sm">{migration.errorMessage}</p>
                      </div>
                    </div>
                  )}
                </div>
              </div>
            )
          })}
        </div>
      ) : (
        <div className="text-center py-12">
          <div className="max-w-md mx-auto">
            <div className="bg-slate-100 rounded-full w-16 h-16 flex items-center justify-center mx-auto mb-4">
              <FaBolt className="w-8 h-8 text-slate-500" />
            </div>
            <h3 className="text-lg font-medium text-slate-900 mb-2">
              {searchTerm || filterStatus !== 'all'
                ? translate('::App.DeveloperKit.Migration.NoMigrationsFound')
                : translate('::App.DeveloperKit.Migration.NoMigrationsYet')}
            </h3>
            <p className="text-slate-600">
              {searchTerm || filterStatus !== 'all'
                ? translate('::App.DeveloperKit.Migration.NoMigrationsAdjustSearch')
                : translate('::App.DeveloperKit.Migration.CreateEntitiesForMigration')}
            </p>
          </div>
        </div>
      )}
    </div>
  )
}

export default MigrationManager
