import { useState, useEffect } from 'react'
import {
  getFactorioSaves,
  getFactorioPresets,
  getFactorioPreset,
  getFactorioTemplates,
  createFactorioTemplate,
  deleteFactorioTemplate,
  createFactorioWorld,
  deleteFactorioSave,
  getFactorioWorldSettings,
  serverAction
} from '../api'
import WorldGenForm from './WorldGenForm'

export default function FactorioWorldManager({ server, token, onServerAction }) {
  const [saves, setSaves] = useState([])
  const [templates, setTemplates] = useState([])
  const [presets, setPresets] = useState([])
  const [defaultSettings, setDefaultSettings] = useState(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')
  const [showCreateWorld, setShowCreateWorld] = useState(false)
  const [newWorldName, setNewWorldName] = useState('')
  const [worldSettings, setWorldSettings] = useState(null)
  const [creating, setCreating] = useState(false)
  const [deleteConfirm, setDeleteConfirm] = useState(null)
  const [actionLoading, setActionLoading] = useState(null)
  const [viewingSettings, setViewingSettings] = useState(null)
  const [settingsData, setSettingsData] = useState(null)
  const [settingsLoading, setSettingsLoading] = useState(false)

  const fetchData = async () => {
    try {
      setLoading(true)
      const [savesData, presetsData, templatesData] = await Promise.all([
        getFactorioSaves(token),
        getFactorioPresets(token),
        getFactorioTemplates(token)
      ])
      setSaves(savesData.saves || [])
      setPresets(presetsData.presets || [])
      setDefaultSettings(presetsData.defaultSettings)
      setWorldSettings(presetsData.defaultSettings)
      setTemplates(templatesData.templates || [])
      setError('')
    } catch (err) {
      setError(err.message)
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    fetchData()
  }, [token])

  const handleLoadPreset = async (presetName) => {
    try {
      const data = await getFactorioPreset(token, presetName)
      setWorldSettings(data.settings)
    } catch (err) {
      setError(err.message)
    }
  }

  const handleLoadTemplate = (templateId) => {
    const template = templates.find(t => t.id === templateId)
    if (template) {
      setWorldSettings(template.settings)
    }
  }

  const handleSaveTemplate = async (name) => {
    try {
      await createFactorioTemplate(token, name, worldSettings)
      const templatesData = await getFactorioTemplates(token)
      setTemplates(templatesData.templates || [])
    } catch (err) {
      setError(err.message)
    }
  }

  const handleDeleteTemplate = async (id) => {
    try {
      await deleteFactorioTemplate(token, id)
      setTemplates(templates.filter(t => t.id !== id))
    } catch (err) {
      setError(err.message)
    }
  }

  const handleCreateWorld = async () => {
    if (!newWorldName.trim()) {
      setError('World name is required')
      return
    }

    if (!/^[a-zA-Z0-9_-]+$/.test(newWorldName)) {
      setError('World name can only contain letters, numbers, hyphens and underscores')
      return
    }

    try {
      setCreating(true)
      setError('')
      await createFactorioWorld(token, newWorldName, worldSettings)
      setShowCreateWorld(false)
      setNewWorldName('')
      setWorldSettings(defaultSettings)
      await fetchData()
    } catch (err) {
      setError(err.message)
    } finally {
      setCreating(false)
    }
  }

  const handleStartWithSave = async (saveName) => {
    try {
      setActionLoading(saveName)
      await serverAction(token, server.id, 'start', { save: saveName })
      if (onServerAction) onServerAction()
    } catch (err) {
      setError(err.message)
    } finally {
      setActionLoading(null)
    }
  }

  const handleDeleteSave = async (saveName) => {
    try {
      setActionLoading(saveName)
      await deleteFactorioSave(token, saveName)
      setDeleteConfirm(null)
      await fetchData()
    } catch (err) {
      setError(err.message)
    } finally {
      setActionLoading(null)
    }
  }

  const handleViewSettings = async (saveName) => {
    try {
      setSettingsLoading(true)
      setViewingSettings(saveName)
      const data = await getFactorioWorldSettings(token, saveName)
      setSettingsData(data)
    } catch (err) {
      setError(err.message)
      setViewingSettings(null)
    } finally {
      setSettingsLoading(false)
    }
  }

  const closeSettingsModal = () => {
    setViewingSettings(null)
    setSettingsData(null)
  }

  // Format setting value for display
  const formatSettingValue = (value) => {
    if (value === 0) return 'None'
    if (value <= 0.2) return 'Very Low'
    if (value <= 0.6) return 'Low'
    if (value <= 1.2) return 'Normal'
    if (value <= 2.5) return 'High'
    return 'Very High'
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center py-12">
        <div className="text-neutral-400">Loading world data...</div>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {error && (
        <div className="alert alert-error">
          {error}
        </div>
      )}

      {/* Create World Modal */}
      {showCreateWorld && (
        <div className="modal-backdrop" onClick={() => !creating && setShowCreateWorld(false)}>
          <div className="modal max-w-3xl fade-in-scale" onClick={e => e.stopPropagation()}>
            <div className="modal-header">
              <h3 className="modal-title">Create New World</h3>
              <button
                onClick={() => !creating && setShowCreateWorld(false)}
                disabled={creating}
                className="btn btn-ghost p-1"
              >
                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            </div>

            <div className="modal-body">
              <div className="form-group">
                <label className="form-label">World Name</label>
                <input
                  type="text"
                  value={newWorldName}
                  onChange={(e) => setNewWorldName(e.target.value)}
                  placeholder="my-new-world"
                  disabled={creating}
                  className="input"
                />
              </div>

              <WorldGenForm
                settings={worldSettings}
                onSettingsChange={setWorldSettings}
                presets={presets}
                templates={templates}
                onLoadPreset={handleLoadPreset}
                onLoadTemplate={handleLoadTemplate}
                onSaveTemplate={handleSaveTemplate}
              />
            </div>

            <div className="modal-footer">
              <button
                onClick={() => setShowCreateWorld(false)}
                disabled={creating}
                className="btn btn-secondary"
              >
                Cancel
              </button>
              <button
                onClick={handleCreateWorld}
                disabled={creating || !newWorldName.trim()}
                className="btn btn-primary"
              >
                {creating ? 'Creating...' : 'Create World'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Delete Confirmation Modal */}
      {deleteConfirm && (
        <div className="modal-backdrop" onClick={() => setDeleteConfirm(null)}>
          <div className="modal max-w-md fade-in-scale" onClick={e => e.stopPropagation()}>
            <div className="modal-header">
              <h3 className="modal-title">Delete Save?</h3>
            </div>
            <div className="modal-body">
              <p className="text-neutral-300">
                Are you sure you want to delete <span className="text-white font-medium">{deleteConfirm}</span>? This action cannot be undone.
              </p>
            </div>
            <div className="modal-footer">
              <button
                onClick={() => setDeleteConfirm(null)}
                className="btn btn-secondary"
              >
                Cancel
              </button>
              <button
                onClick={() => handleDeleteSave(deleteConfirm)}
                disabled={actionLoading === deleteConfirm}
                className="btn btn-destructive"
              >
                {actionLoading === deleteConfirm ? 'Deleting...' : 'Delete'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* View Settings Modal */}
      {viewingSettings && (
        <div className="modal-backdrop" onClick={closeSettingsModal}>
          <div className="modal max-w-2xl fade-in-scale" onClick={e => e.stopPropagation()}>
            <div className="modal-header">
              <h3 className="modal-title">World Settings: {viewingSettings}</h3>
              <button onClick={closeSettingsModal} className="btn btn-ghost p-1">
                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            </div>
            <div className="modal-body">
              {settingsLoading ? (
                <div className="text-center py-8 text-neutral-400">Loading settings...</div>
              ) : settingsData?.legacy ? (
                <div className="bg-neutral-800/50 rounded-lg p-6 text-center">
                  <div className="text-amber-400 mb-2">⚠️ Legacy World</div>
                  <p className="text-neutral-400 text-sm">
                    {settingsData.message}
                  </p>
                </div>
              ) : settingsData?.settings ? (
                <div className="space-y-4">
                  {settingsData.createdAt && (
                    <div className="text-neutral-500 text-xs mb-4">
                      Created: {new Date(settingsData.createdAt).toLocaleString()}
                    </div>
                  )}

                  {/* Terrain Settings */}
                  <div>
                    <h4 className="text-sm font-medium text-neutral-300 mb-2">Terrain</h4>
                    <div className="grid grid-cols-2 gap-2 text-sm">
                      <div className="flex justify-between p-2 bg-neutral-800/30 rounded">
                        <span className="text-neutral-400">Water</span>
                        <span className="text-white">{formatSettingValue(settingsData.settings.autoplace_controls?.water?.frequency)}</span>
                      </div>
                      <div className="flex justify-between p-2 bg-neutral-800/30 rounded">
                        <span className="text-neutral-400">Trees</span>
                        <span className="text-white">{formatSettingValue(settingsData.settings.autoplace_controls?.trees?.frequency)}</span>
                      </div>
                      <div className="flex justify-between p-2 bg-neutral-800/30 rounded">
                        <span className="text-neutral-400">Cliffs</span>
                        <span className="text-white">{formatSettingValue(settingsData.settings.cliff_settings?.richness)}</span>
                      </div>
                      <div className="flex justify-between p-2 bg-neutral-800/30 rounded">
                        <span className="text-neutral-400">Starting Area</span>
                        <span className="text-white">{formatSettingValue(settingsData.settings.starting_area)}</span>
                      </div>
                    </div>
                  </div>

                  {/* Resource Settings */}
                  <div>
                    <h4 className="text-sm font-medium text-neutral-300 mb-2">Resources</h4>
                    <div className="grid grid-cols-1 gap-2 text-sm">
                      {['iron-ore', 'copper-ore', 'coal', 'stone', 'uranium-ore', 'crude-oil'].map((resource) => {
                        const ctrl = settingsData.settings.autoplace_controls?.[resource]
                        const displayName = resource.replace('-ore', '').replace('-', ' ').replace(/\b\w/g, c => c.toUpperCase())
                        return (
                          <div key={resource} className="flex justify-between p-2 bg-neutral-800/30 rounded">
                            <span className="text-neutral-400">{displayName}</span>
                            <span className="text-white text-xs">
                              Freq: {formatSettingValue(ctrl?.frequency)} · Size: {formatSettingValue(ctrl?.size)} · Rich: {formatSettingValue(ctrl?.richness)}
                            </span>
                          </div>
                        )
                      })}
                    </div>
                  </div>

                  {/* Enemy Settings */}
                  <div>
                    <h4 className="text-sm font-medium text-neutral-300 mb-2">Enemies</h4>
                    <div className="grid grid-cols-2 gap-2 text-sm">
                      <div className="flex justify-between p-2 bg-neutral-800/30 rounded">
                        <span className="text-neutral-400">Biter Bases</span>
                        <span className="text-white">{formatSettingValue(settingsData.settings.autoplace_controls?.['enemy-base']?.frequency)}</span>
                      </div>
                      <div className="flex justify-between p-2 bg-neutral-800/30 rounded">
                        <span className="text-neutral-400">Peaceful Mode</span>
                        <span className="text-white">{settingsData.settings.peaceful_mode ? 'Yes' : 'No'}</span>
                      </div>
                    </div>
                  </div>

                  {/* Seed */}
                  {settingsData.settings.seed !== undefined && (
                    <div>
                      <h4 className="text-sm font-medium text-neutral-300 mb-2">Advanced</h4>
                      <div className="p-2 bg-neutral-800/30 rounded text-sm">
                        <span className="text-neutral-400">Seed: </span>
                        <span className="text-white font-mono">{settingsData.settings.seed || 'Random'}</span>
                      </div>
                    </div>
                  )}
                </div>
              ) : (
                <div className="text-center py-8 text-neutral-400">No settings data available</div>
              )}
            </div>
            <div className="modal-footer">
              <button onClick={closeSettingsModal} className="btn btn-secondary">
                Close
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Header */}
      <div className="flex items-center justify-between">
        <h3 className="text-sm font-medium text-neutral-300">Saved Worlds</h3>
        <button
          onClick={() => setShowCreateWorld(true)}
          className="btn btn-primary"
        >
          + Create New
        </button>
      </div>

      {/* Saves List */}
      {saves.length === 0 ? (
        <div className="card p-8 text-center">
          <div className="text-neutral-400">No saved worlds found</div>
          <div className="text-neutral-500 text-sm mt-1">Create a new world to get started</div>
        </div>
      ) : (
        <div className="space-y-2">
          {saves.map((save) => (
            <div
              key={save.name}
              className="card p-4 card-clickable"
            >
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-4">
                  <span className="text-2xl">🌍</span>
                  <div>
                    <div className="text-white font-medium">{save.name}</div>
                    <div className="text-neutral-500 text-xs mt-1">
                      {save.size} · {save.modified}
                    </div>
                  </div>
                </div>
                <div className="flex items-center gap-2">
                  <button
                    onClick={() => handleViewSettings(save.name)}
                    className="btn btn-ghost text-neutral-400 hover:text-white"
                    title="View world settings"
                  >
                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg>
                  </button>
                  <button
                    onClick={() => handleStartWithSave(save.name)}
                    disabled={actionLoading === save.name || server.running}
                    className="btn btn-primary text-sm"
                    title={server.running ? 'Stop server first' : 'Start with this save'}
                  >
                    {actionLoading === save.name ? '...' : 'Start'}
                  </button>
                  <button
                    onClick={() => setDeleteConfirm(save.name)}
                    disabled={actionLoading === save.name}
                    className="btn btn-ghost text-red-400 hover:text-red-300 hover:bg-red-500/10"
                  >
                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                    </svg>
                  </button>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Templates Section */}
      {templates.length > 0 && (
        <div className="mt-8">
          <h3 className="text-sm font-medium text-neutral-300 mb-3">Saved Templates</h3>
          <div className="flex flex-wrap gap-2">
            {templates.map((template) => (
              <div
                key={template.id}
                className="badge badge-secondary flex items-center gap-2 group"
              >
                <span>{template.name}</span>
                <button
                  onClick={() => handleDeleteTemplate(template.id)}
                  className="text-neutral-500 hover:text-red-400 opacity-0 group-hover:opacity-100 transition-opacity"
                >
                  ×
                </button>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  )
}
