'use client'

import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Button } from '@/components/ui/button'
import { Header } from '@/components/layout/header'
import { LevelTable } from '@/components/levels/level-table'
import { LevelDialog } from '@/components/levels/level-dialog'
import { BatchImportDialog } from '@/components/levels/batch-import-dialog'
import { DeleteConfirmDialog } from '@/components/levels/delete-confirm-dialog'
import { Spinner } from '@/components/ui/spinner'
import { Level, LevelFormData } from '@/types'
import { Plus, Upload } from 'lucide-react'
import { apiFetch } from '@/lib/api'

export default function LevelsPage() {
  const queryClient = useQueryClient()
  const [isDialogOpen, setIsDialogOpen] = useState(false)
  const [isBatchOpen, setIsBatchOpen] = useState(false)
  const [editingLevel, setEditingLevel] = useState<Level | null>(null)
  const [deletingLevel, setDeletingLevel] = useState<Level | null>(null)

  // Fetch levels
  const { data: levels, isLoading, error } = useQuery<Level[]>({
    queryKey: ['levels'],
    queryFn: async () => {
      const res = await apiFetch('/api/levels')
      if (!res.ok) throw new Error('Failed to fetch levels')
      return res.json()
    },
  })

  // Create level mutation
  const createMutation = useMutation({
    mutationFn: async (data: LevelFormData) => {
      const res = await apiFetch('/api/levels', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data),
      })
      if (!res.ok) {
        const error = await res.json()
        throw new Error(error.error || 'Failed to create level')
      }
      return res.json()
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['levels'] })
    },
  })

  // Update level mutation
  const updateMutation = useMutation({
    mutationFn: async ({ id, data }: { id: string; data: LevelFormData }) => {
      const res = await apiFetch('/api/levels', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id, ...data }),
      })
      if (!res.ok) {
        const error = await res.json()
        throw new Error(error.error || 'Failed to update level')
      }
      return res.json()
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['levels'] })
    },
  })

  // Delete level mutation
  const deleteMutation = useMutation({
    mutationFn: async (id: string) => {
      const res = await apiFetch(`/api/levels?id=${id}`, {
        method: 'DELETE',
      })
      if (!res.ok) {
        const error = await res.json()
        throw new Error(error.error || 'Failed to delete level')
      }
      return res.json()
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['levels'] })
      setDeletingLevel(null)
    },
  })

  const handleOpenCreate = () => {
    setEditingLevel(null)
    setIsDialogOpen(true)
  }

  const handleOpenEdit = (level: Level) => {
    setEditingLevel(level)
    setIsDialogOpen(true)
  }

  const handleDelete = (id: string) => {
    const target = (levels || []).find((l) => l.id === id)
    if (target) setDeletingLevel(target)
  }

  const handleSubmit = async (data: LevelFormData) => {
    if (editingLevel) {
      await updateMutation.mutateAsync({ id: editingLevel.id, data })
    } else {
      await createMutation.mutateAsync(data)
    }
  }

  if (isLoading) {
    return (
      <div className="h-screen flex items-center justify-center">
        <Spinner size="lg" />
      </div>
    )
  }

  if (error) {
    return (
      <div className="h-screen flex items-center justify-center">
        <div className="text-center">
          <p className="text-red-600">加载失败</p>
          <Button
            className="mt-4"
            onClick={() => queryClient.invalidateQueries({ queryKey: ['levels'] })}
          >
            重试
          </Button>
        </div>
      </div>
    )
  }

  return (
    <div className="h-screen flex flex-col">
      <Header />
      <div className="flex-1 overflow-auto p-6">
        <div>
          <div className="flex items-center justify-between mb-6">
            <div>
              <h1 className="text-2xl font-bold">关卡配置</h1>
              <p className="text-gray-500 mt-1">
                共 {levels?.length || 0} 个关卡
              </p>
            </div>
            <div className="flex items-center gap-2">
              <Button variant="outline" onClick={() => setIsBatchOpen(true)}>
                <Upload className="h-4 w-4 mr-2" />
                批量导入
              </Button>
              <Button onClick={handleOpenCreate}>
                <Plus className="h-4 w-4 mr-2" />
                添加关卡
              </Button>
            </div>
          </div>

          <LevelTable
            levels={levels || []}
            onEdit={handleOpenEdit}
            onDelete={handleDelete}
          />
        </div>
      </div>

      <LevelDialog
        open={isDialogOpen}
        onOpenChange={setIsDialogOpen}
        level={editingLevel}
        totalCount={levels?.length || 0}
        currentIndex={
          editingLevel
            ? (levels || []).findIndex((l) => l.id === editingLevel.id)
            : null
        }
        onSubmit={handleSubmit}
      />

      <BatchImportDialog
        open={isBatchOpen}
        onOpenChange={setIsBatchOpen}
        onSuccess={() =>
          queryClient.invalidateQueries({ queryKey: ['levels'] })
        }
      />

      <DeleteConfirmDialog
        open={!!deletingLevel}
        onOpenChange={(next) => {
          if (!next) setDeletingLevel(null)
        }}
        level={deletingLevel}
        index={
          deletingLevel
            ? (levels || []).findIndex((l) => l.id === deletingLevel.id)
            : undefined
        }
        isLoading={deleteMutation.isPending}
        onConfirm={() => {
          if (deletingLevel) deleteMutation.mutate(deletingLevel.id)
        }}
      />
    </div>
  )
}
