import { useState, useEffect, useCallback } from 'react'
import { Sidebar } from './components/Sidebar'
import { Editor } from './components/Editor'
import { Preview } from './components/Preview'
import { Header } from './components/Header'
import type { Theme, FileItem } from './types'
import { api } from './api'

function App() {
  const [theme, setTheme] = useState<Theme>('system')
  const [files, setFiles] = useState<FileItem[]>([])
  const [currentFile, setCurrentFile] = useState<FileItem | null>(null)
  const [content, setContent] = useState('')
  const [isSidebarOpen, setIsSidebarOpen] = useState(true)
  const [isPreviewOpen, setIsPreviewOpen] = useState(true)
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  // Initialize theme
  useEffect(() => {
    const savedTheme = localStorage.getItem('theme') as Theme
    if (savedTheme) {
      setTheme(savedTheme)
    }
  }, [])

  // Apply theme
  useEffect(() => {
    const root = window.document.documentElement
    root.classList.remove('light', 'dark')

    if (theme === 'system') {
      const systemTheme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
      root.classList.add(systemTheme)
    } else {
      root.classList.add(theme)
    }

    localStorage.setItem('theme', theme)
  }, [theme])

  // Load files on mount
  useEffect(() => {
    loadFiles()
  }, [])

  const loadFiles = async () => {
    try {
      setIsLoading(true)
      setError(null)
      const fileNames = await api.listFiles()
      const fileItems: FileItem[] = fileNames.map(name => ({
        id: name,
        name,
        content: '',
      }))
      setFiles(fileItems)
    } catch (err) {
      setError('Failed to load files')
      console.error(err)
    } finally {
      setIsLoading(false)
    }
  }

  const handleCreateFile = async (name: string) => {
    try {
      setError(null)
      await api.createFile(name, '')
      const newFile: FileItem = { id: name, name, content: '' }
      setFiles([newFile, ...files])
      setCurrentFile(newFile)
      setContent('')
    } catch (err) {
      setError('Failed to create file')
      console.error(err)
    }
  }

  const handleOpenFile = async (file: FileItem) => {
    try {
      setError(null)
      setIsLoading(true)
      const fileData = await api.getFile(file.name)
      const updatedFile = { ...file, content: fileData.content }
      setCurrentFile(updatedFile)
      setContent(fileData.content)
    } catch (err) {
      setError('Failed to open file')
      console.error(err)
    } finally {
      setIsLoading(false)
    }
  }

  const handleSaveFile = async () => {
    if (!currentFile) return
    try {
      setError(null)
      await api.updateFile(currentFile.name, content)
      const updatedFiles = files.map(f =>
        f.id === currentFile.id ? { ...f, content } : f
      )
      setFiles(updatedFiles)
      setCurrentFile({ ...currentFile, content })
    } catch (err) {
      setError('Failed to save file')
      console.error(err)
    }
  }

  const handleDeleteFile = async (file: FileItem) => {
    try {
      setError(null)
      await api.deleteFile(file.name)
      setFiles(files.filter(f => f.id !== file.id))
      if (currentFile?.id === file.id) {
        setCurrentFile(null)
        setContent('')
      }
    } catch (err) {
      setError('Failed to delete file')
      console.error(err)
    }
  }

  const handleContentChange = useCallback((newContent: string) => {
    setContent(newContent)
  }, [])

  return (
    <div className="min-h-screen bg-white dark:bg-gray-900 text-gray-900 dark:text-gray-100 transition-colors duration-200">
      <Header
        theme={theme}
        onThemeChange={setTheme}
        currentFile={currentFile}
        onSave={handleSaveFile}
        onToggleSidebar={() => setIsSidebarOpen(!isSidebarOpen)}
        onTogglePreview={() => setIsPreviewOpen(!isPreviewOpen)}
        isSidebarOpen={isSidebarOpen}
        isPreviewOpen={isPreviewOpen}
      />

      {error && (
        <div className="bg-red-100 dark:bg-red-900 text-red-800 dark:text-red-200 px-4 py-2 text-sm">
          {error}
        </div>
      )}

      <div className="flex h-[calc(100vh-64px)]">
        {isSidebarOpen && (
          <Sidebar
            files={files}
            currentFile={currentFile}
            onCreateFile={handleCreateFile}
            onOpenFile={handleOpenFile}
            onDeleteFile={handleDeleteFile}
            isLoading={isLoading}
          />
        )}

        <div className="flex-1 flex">
          <div className={`flex-1 ${isPreviewOpen ? 'w-1/2' : 'w-full'}`}>
            <Editor
              content={content}
              onChange={handleContentChange}
              placeholder={currentFile ? "Start typing..." : "Select or create a file to start editing"}
              disabled={!currentFile}
            />
          </div>

          {isPreviewOpen && (
            <div className="flex-1 w-1/2 border-l border-gray-200 dark:border-gray-700">
              <Preview content={content} />
            </div>
          )}
        </div>
      </div>
    </div>
  )
}

export default App
