import { useState, useEffect } from 'react'
import { Plus, Search, RefreshCw, Edit, Trash2, Database, CheckCircle2, XCircle } from 'lucide-react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Switch } from '@/components/ui/switch'

import { getStorageConfigList, createStorageConfig, updateStorageConfig, deleteStorageConfig, setDefaultStorageConfig } from '@/api/system/file'
import type { StorageConfig } from '@/api/system'

const STORAGE_TYPES = [
  { label: '自建 MinIO', value: 'minio' },
  { label: '阿里云 OSS', value: 'aliyun' },
  { label: '腾讯云 COS', value: 'tencent' },
  { label: '七牛云', value: 'qiniu' },
]

export default function StorageConfigs() {
  const [configs, setConfigs] = useState<StorageConfig[]>([])
  const [total, setTotal] = useState(0)
  const [loading, setLoading] = useState(false)
  const [search, setSearch] = useState({ name: '', type: '' })
  
  // Dialog State
  const [dialogOpen, setDialogOpen] = useState(false)
  const [editingConfig, setEditingConfig] = useState<StorageConfig | null>(null)
  const [confirmDialogOpen, setConfirmDialogOpen] = useState(false)
  const [confirmAction, setConfirmAction] = useState<{ type: 'delete' | 'setDefault', id: string } | null>(null)
  
  const [formData, setFormData] = useState<Partial<StorageConfig>>({
    name: '', type: 'minio', endpoint: '', accessKeyId: '', accessKeySecret: '', 
    bucketName: '', bucketUrl: '', region: '', status: 1, remark: ''
  })

  const fetchConfigs = async () => {
    setLoading(true)
    try {
      const res = await getStorageConfigList({ current: 1, pageSize: 20, ...search })
      if (res) {
        setConfigs(res.list)
        setTotal(res.total)
      }
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => { 
    fetchConfigs()
  }, [])

  const handleSearch = () => fetchConfigs()
  const handleReset = () => { setSearch({ name: '', type: '' }); setTimeout(() => fetchConfigs(), 0) }

  const openCreateDialog = () => {
    setEditingConfig(null)
    setFormData({
      name: '', type: 'minio', endpoint: '', accessKeyId: '', accessKeySecret: '', 
      bucketName: '', bucketUrl: '', region: '', status: 1, remark: ''
    })
    setDialogOpen(true)
  }

  const openEditDialog = (conf: StorageConfig) => {
    setEditingConfig(conf)
    setFormData({ ...conf })
    setDialogOpen(true)
  }

  const handleSave = async () => {
    if (editingConfig) await updateStorageConfig({ id: editingConfig.id, ...formData })
    else await createStorageConfig(formData)
    setDialogOpen(false)
    fetchConfigs()
  }

  const handleDelete = (id: string) => {
    setConfirmAction({ type: 'delete', id })
    setConfirmDialogOpen(true)
  }

  const handleSetDefault = (id: string) => {
    setConfirmAction({ type: 'setDefault', id })
    setConfirmDialogOpen(true)
  }

  const executeConfirmAction = async () => {
    if (!confirmAction) return
    if (confirmAction.type === 'delete') {
      await deleteStorageConfig([confirmAction.id])
    } else if (confirmAction.type === 'setDefault') {
      await setDefaultStorageConfig(confirmAction.id)
    }
    setConfirmDialogOpen(false)
    setConfirmAction(null)
    fetchConfigs()
  }

  return (
    <div className="space-y-6 animate-fadeIn">
      <div>
        <h1 className="text-2xl font-bold tracking-tight">存储引擎配置</h1>
        <p className="text-muted-foreground mt-1">动态管理多云厂商的OSS配置，可随时切换默认的上传通道。</p>
      </div>

      <Card className="border-border/60 shadow-soft">
        <CardHeader className="pb-3 border-b border-border/40">
          <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
            <CardTitle className="text-lg flex items-center gap-2">
              <Database className="h-5 w-5 text-primary" /> 引擎列表
            </CardTitle>
            
            <div className="flex flex-wrap items-center gap-3">
              <Select value={search.type} onValueChange={(val) => setSearch({ ...search, type: val === 'all' ? '' : val })}>
                <SelectTrigger className="w-[140px] h-9">
                  <SelectValue placeholder="所有类型" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">所有类型</SelectItem>
                  {STORAGE_TYPES.map(t => <SelectItem key={t.value} value={t.value}>{t.label}</SelectItem>)}
                </SelectContent>
              </Select>
              
              <div className="relative">
                <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
                <Input
                  placeholder="搜索配置名称..."
                  className="pl-9 w-48 h-9"
                  value={search.name}
                  onChange={e => setSearch({ ...search, name: e.target.value })}
                  onKeyDown={e => e.key === 'Enter' && handleSearch()}
                />
              </div>
              <Button variant="outline" size="sm" onClick={handleReset} className="h-9 px-3">重置</Button>
              <Button size="sm" onClick={openCreateDialog} className="h-9 gap-1.5">
                <Plus className="h-4 w-4" /> 新增配置
              </Button>
            </div>
          </div>
        </CardHeader>
        <CardContent className="p-0">
          <Table>
            <TableHeader className="bg-muted/30">
              <TableRow>
                <TableHead className="pl-6">配置名称</TableHead>
                <TableHead>厂商类型</TableHead>
                <TableHead>Bucket / Endpoint</TableHead>
                <TableHead>默认引擎</TableHead>
                <TableHead>状态</TableHead>
                <TableHead className="text-right pr-6">操作</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {loading ? (
                <TableRow>
                  <TableCell colSpan={6} className="h-32 text-center text-muted-foreground">
                    <RefreshCw className="h-6 w-6 animate-spin mx-auto mb-2 text-primary/50" /> 加载中...
                  </TableCell>
                </TableRow>
              ) : configs.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={6} className="h-32 text-center text-muted-foreground">暂无数据</TableCell>
                </TableRow>
              ) : (
                configs.map(conf => (
                  <TableRow key={conf.id} className="hover:bg-muted/20">
                    <TableCell className="font-medium pl-6">{conf.name}</TableCell>
                    <TableCell>
                      <span className="inline-flex items-center px-2 py-1 rounded text-xs font-medium bg-blue-500/10 text-blue-500 border border-blue-500/20">
                        {STORAGE_TYPES.find(t => t.value === conf.type)?.label || conf.type}
                      </span>
                    </TableCell>
                    <TableCell className="text-sm">
                      <div className="font-medium">{conf.bucketName}</div>
                      <div className="text-muted-foreground text-xs mt-0.5 max-w-[200px] truncate" title={conf.endpoint}>{conf.endpoint}</div>
                    </TableCell>
                    <TableCell>
                      {conf.isDefault === 1 ? (
                        <div className="flex items-center gap-1.5 text-emerald-500 text-sm font-medium">
                          <CheckCircle2 className="h-4 w-4" /> 生效中
                        </div>
                      ) : (
                        <Button variant="outline" size="sm" className="h-7 text-xs px-2" onClick={() => handleSetDefault(conf.id)}>
                          设为默认
                        </Button>
                      )}
                    </TableCell>
                    <TableCell>
                      {conf.status === 1 ? <span className="text-emerald-500 text-sm">启用</span> : <span className="text-red-500 text-sm">停用</span>}
                    </TableCell>
                    <TableCell className="text-right pr-6">
                      <div className="flex items-center justify-end gap-2">
                        <Button variant="ghost" size="sm" className="h-8 gap-1" onClick={() => openEditDialog(conf)}>
                          <Edit className="h-3.5 w-3.5 text-blue-500" /> 编辑
                        </Button>
                        <Button variant="ghost" size="sm" className="h-8 gap-1 hover:text-red-500" onClick={() => handleDelete(conf.id)}>
                          <Trash2 className="h-3.5 w-3.5 text-red-500" /> 删除
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
          
          <div className="flex items-center justify-between px-6 py-4 border-t border-border/40 text-sm text-muted-foreground">
            <div>共 {total} 条记录</div>
            <div className="flex items-center gap-2">
              <Button variant="outline" size="sm" disabled>上一页</Button>
              <Button variant="outline" size="sm" disabled>下一页</Button>
            </div>
          </div>
        </CardContent>
      </Card>

      <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
        <DialogContent className="sm:max-w-[550px]">
          <DialogHeader>
            <DialogTitle>{editingConfig ? '编辑存储引擎配置' : '新增存储引擎配置'}</DialogTitle>
            <DialogDescription>
              {editingConfig ? '修改当前配置项，修改 AccessKey 等凭证信息可能影响线上服务。' : '添加新的 OSS 凭证配置，之后可以将其切换为默认引擎。'}
            </DialogDescription>
          </DialogHeader>
          <div className="grid grid-cols-2 gap-4 py-4">
            <div className="col-span-2 sm:col-span-1 space-y-2">
              <Label htmlFor="name">配置名称</Label>
              <Input id="name" value={formData.name} onChange={e => setFormData({ ...formData, name: e.target.value })} placeholder="例如：阿里云北京节点" />
            </div>
            <div className="col-span-2 sm:col-span-1 space-y-2">
              <Label>存储厂商类型</Label>
              <Select value={formData.type} onValueChange={(val) => setFormData({ ...formData, type: val })}>
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {STORAGE_TYPES.map(t => <SelectItem key={t.value} value={t.value}>{t.label}</SelectItem>)}
                </SelectContent>
              </Select>
            </div>

            <div className="col-span-2 space-y-2">
              <Label htmlFor="endpoint">Endpoint / 接口地址</Label>
              <Input id="endpoint" value={formData.endpoint} onChange={e => setFormData({ ...formData, endpoint: e.target.value })} placeholder="例如：oss-cn-beijing.aliyuncs.com" />
            </div>

            <div className="col-span-2 sm:col-span-1 space-y-2">
              <Label htmlFor="accessKeyId">AccessKey ID</Label>
              <Input id="accessKeyId" value={formData.accessKeyId} onChange={e => setFormData({ ...formData, accessKeyId: e.target.value })} placeholder="云厂商提供的 AK" />
            </div>
            <div className="col-span-2 sm:col-span-1 space-y-2">
              <Label htmlFor="accessKeySecret">AccessKey Secret</Label>
              <Input id="accessKeySecret" type="password" value={formData.accessKeySecret} onChange={e => setFormData({ ...formData, accessKeySecret: e.target.value })} placeholder="云厂商提供的 SK" />
            </div>

            <div className="col-span-2 sm:col-span-1 space-y-2">
              <Label htmlFor="bucketName">Bucket Name (存储桶)</Label>
              <Input id="bucketName" value={formData.bucketName} onChange={e => setFormData({ ...formData, bucketName: e.target.value })} placeholder="例如：my-sundynix-app" />
            </div>
            <div className="col-span-2 sm:col-span-1 space-y-2">
              <Label htmlFor="region">Region (区域代号)</Label>
              <Input id="region" value={formData.region} onChange={e => setFormData({ ...formData, region: e.target.value })} placeholder="选填，如：ap-guangzhou" />
            </div>

            <div className="col-span-2 space-y-2">
              <Label htmlFor="bucketUrl">Bucket 外部访问域名 (CDN/直连)</Label>
              <Input id="bucketUrl" value={formData.bucketUrl} onChange={e => setFormData({ ...formData, bucketUrl: e.target.value })} placeholder="例如：https://my-bucket.oss-cn-beijing.aliyuncs.com" />
            </div>

            <div className="col-span-2 flex items-center justify-between border rounded-md p-3">
              <div className="space-y-0.5">
                <Label>配置状态</Label>
                <p className="text-[0.8rem] text-muted-foreground">启用后才允许设置为默认引擎。</p>
              </div>
              <Switch checked={formData.status === 1} onCheckedChange={(c) => setFormData({ ...formData, status: c ? 1 : 0 })} />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setDialogOpen(false)}>取消</Button>
            <Button onClick={handleSave}>保存配置</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog open={confirmDialogOpen} onOpenChange={setConfirmDialogOpen}>
        <DialogContent className="sm:max-w-[425px]">
          <DialogHeader>
            <DialogTitle>{confirmAction?.type === 'delete' ? '确认删除' : '设为默认引擎'}</DialogTitle>
            <DialogDescription className="pt-2">
              {confirmAction?.type === 'delete' 
                ? '确定要删除该存储配置吗？此操作不可逆，相关文件将无法使用该配置进行读取！' 
                : '确定将该配置设为当前系统的全局默认上传引擎吗？新的上传操作将立即切换到此厂商。'}
            </DialogDescription>
          </DialogHeader>
          <DialogFooter className="mt-4">
            <Button variant="outline" onClick={() => setConfirmDialogOpen(false)}>取消</Button>
            <Button variant={confirmAction?.type === 'delete' ? 'destructive' : 'default'} onClick={executeConfirmAction}>
              {confirmAction?.type === 'delete' ? '确定删除' : '确定切换'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
