import { useState } from 'react'
import { useCreateModel, useUpdateModel } from '@/hooks/useModels'
import { useProviders, useCreateProvider, useUpdateProvider, useDeleteProvider } from '@/hooks/useProviders'
import type { Provider, Model, UpdateProviderInput, UpdateModelInput } from '@/types'
import { ModelForm } from './ModelForm'
import { ProviderForm } from './ProviderForm'
import { ProviderTable } from './ProviderTable'

export default function ProvidersPage() {
  const { data: providers = [], isLoading } = useProviders()
  const createProvider = useCreateProvider()
  const updateProvider = useUpdateProvider()
  const deleteProvider = useDeleteProvider()
  const createModel = useCreateModel()
  const updateModel = useUpdateModel()

  const [providerFormOpen, setProviderFormOpen] = useState(false)
  const [editingProvider, setEditingProvider] = useState<Provider | undefined>()
  const [modelFormOpen, setModelFormOpen] = useState(false)
  const [editingModel, setEditingModel] = useState<Model | undefined>()
  const [modelFormProviderId, setModelFormProviderId] = useState('')

  return (
    <div>
      <ProviderTable
        providers={providers}
        loading={isLoading}
        onAdd={() => {
          setEditingProvider(undefined)
          setProviderFormOpen(true)
        }}
        onEdit={(provider) => {
          setEditingProvider(provider)
          setProviderFormOpen(true)
        }}
        onDelete={(id) => deleteProvider.mutate(id)}
        onAddModel={(providerId) => {
          setEditingModel(undefined)
          setModelFormProviderId(providerId)
          setModelFormOpen(true)
        }}
        onEditModel={(model) => {
          setEditingModel(model)
          setModelFormProviderId(model.providerId)
          setModelFormOpen(true)
        }}
      />

      <ProviderForm
        open={providerFormOpen}
        provider={editingProvider}
        loading={createProvider.isPending || updateProvider.isPending}
        onSave={async (values) => {
          try {
            if (editingProvider) {
              const input: Partial<UpdateProviderInput> = {}
              if (values.name !== editingProvider.name) input.name = values.name
              if (values.apiKey !== editingProvider.apiKey) input.apiKey = values.apiKey
              if (values.baseUrl !== editingProvider.baseUrl) input.baseUrl = values.baseUrl
              if (values.enabled !== editingProvider.enabled) input.enabled = values.enabled
              await updateProvider.mutateAsync({ id: editingProvider.id, input })
            } else {
              await createProvider.mutateAsync(values)
            }
            setProviderFormOpen(false)
          } catch {
            // 错误已由 hooks 的 onError 处理
          }
        }}
        onCancel={() => setProviderFormOpen(false)}
      />

      <ModelForm
        open={modelFormOpen}
        model={editingModel}
        providerId={modelFormProviderId}
        providers={providers}
        loading={createModel.isPending || updateModel.isPending}
        onSave={async (values) => {
          try {
            if (editingModel) {
              const input: Partial<UpdateModelInput> = {}
              if (values.providerId !== editingModel.providerId) input.providerId = values.providerId
              if (values.modelName !== editingModel.modelName) input.modelName = values.modelName
              if (values.enabled !== editingModel.enabled) input.enabled = values.enabled
              await updateModel.mutateAsync({ id: editingModel.id, input })
            } else {
              await createModel.mutateAsync(values)
            }
            setModelFormOpen(false)
          } catch {
            // 错误已由 hooks 的 onError 处理
          }
        }}
        onCancel={() => setModelFormOpen(false)}
      />
    </div>
  )
}
