import { memo, useEffect, useState } from 'react'
import { useMemoizedFn } from 'ahooks'
import { cn } from '@/utils/cn'
import { Inbox } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { Label } from '@/components/ui/label'
import { toast } from 'sonner'

export interface SkillFormState {
  name: string
  description?: string
  file?: { file: File; fileList: File[] }
}

interface SkillFormProps {
  values?: { name: string; description?: string }
  className?: string
  teamId: string
  onBack: () => void
  onSave: (values: SkillFormState) => Promise<void>
}

const name_required_text = '请输入SKILL工具名称'
const file_tooltip_text = '仅支持上传 .zip 文件'

export const SkillForm = memo<SkillFormProps>(
  ({ className, values, onBack, onSave }) => {
    const [name, setName] = useState(values?.name || '')
    const [description, setDescription] = useState(values?.description || '')
    const [file, setFile] = useState<File | null>(null)
    const [loading, setLoading] = useState(false)

    const isEdit = !!values

    useEffect(() => {
      if (values) {
        setName(values.name)
        setDescription(values.description || '')
      }
    }, [values])

    const handleSave = useMemoizedFn(async () => {
      if (!name.trim()) {
        toast.error('错误')
        return
      }

      if (!isEdit && !file) {
        toast.error('错误')
        return
      }

      try {
        setLoading(true)
        await onSave({
          name,
          description,
          file: file ? { file: file as File, fileList: [file as File] } : undefined
        })
      } finally {
        setLoading(false)
      }
    })

    const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
      const selectedFile = e.target.files?.[0]
      if (selectedFile) {
        const isZip = selectedFile.type === 'application/zip' || selectedFile.name.endsWith('.zip')
        if (!isZip) {
          toast.error('错误')
          return
        }
        setFile(selectedFile)
      }
    }

    return (
      <div className='flex h-full flex-col bg-transparent text-foreground'>
        <div className={cn('flex-1 p-24px overflow-y-auto space-y-6', className)}>
          <div className='space-y-2 px-[4px]'>
            <Label htmlFor='name' className='mb-[] text-sm font-medium text-foreground'>名称</Label>
            <Input
              id='name'
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder={name_required_text}
              maxLength={100}
              className='mt-[8px] border-border bg-card text-foreground placeholder:text-muted-foreground focus-visible:border-primary focus-visible:ring-2 focus-visible:ring-primary/20 focus-visible:ring-offset-0'
            />
          </div>

          <div className='space-y-2 px-[4px]'>
            <Label htmlFor='description' className='text-sm font-medium text-foreground'>描述</Label>
            <Textarea
              id='description'
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              placeholder='请输入SKILL工具的描述'
              rows={3}
              className='mt-[8px] min-h-[120px] resize-y border-border bg-card text-foreground placeholder:text-muted-foreground focus-visible:border-primary focus-visible:ring-2 focus-visible:ring-primary/20 focus-visible:ring-offset-0'
            />
          </div>

          <div className='space-y-2 px-[4px]'>
            <Label htmlFor='file' className='text-sm font-medium text-foreground'>文件</Label>
            <div className='relative mt-[8px] cursor-pointer rounded-lg border-2 border-dashed border-border bg-card p-8 text-center transition-colors hover:border-primary'>
              <Inbox className='mx-auto mb-4 h-12 w-12 cursor-pointer text-muted-foreground' />
              <input
                id='file'
                type='file'
                accept='.zip,application/zip'
                onChange={handleFileChange}
                className='opacity-0 absolute top-0 left-0 w-full h-full'
              />
              <label htmlFor='file' className='cursor-pointer'>
                <p className='text-sm text-foreground'>
                  {file ? file.name : '点击或拖拽文件到这里上传'}
                </p>
                <p className='mt-2 text-xs text-muted-foreground'>{file_tooltip_text}</p>
              </label>
            </div>
          </div>
        </div>

        <div className='mt-[16px] flex justify-end gap-8px border-t border-border/70 bg-transparent px-24px pb-24px pt-16px'>
          <Button
            variant='outline'
            onClick={onBack}
            className='mr-[8px] hover:bg-transparent hover:border-border hover:text-foreground'
          >
            返回
          </Button>
          <Button
            onClick={handleSave}
            disabled={loading}
          >
            {loading ? '保存中...' : '保存'}
          </Button>
        </div>
      </div>
    )
  },
)

SkillForm.displayName = 'SkillForm'
