import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { zodResolver } from '@hookform/resolvers/zod'
import { useForm } from 'react-hook-form'
import { Plus, Search, Edit, Trash2 } from 'lucide-react'
import { toast } from 'react-toastify'

import { Button } from '@/client/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/client/components/ui/card'
import { Input } from '@/client/components/ui/input'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/client/components/ui/table'
import { Badge } from '@/client/components/ui/badge'
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/client/components/ui/dialog'
import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from '@/client/components/ui/form'
import { DataTablePagination } from '@/client/admin-shadcn/components/DataTablePagination'

import { expressCompanyClient } from '@/client/api'
import type { InferRequestType, InferResponseType } from 'hono/client'
import { CreateExpressCompanyDto, UpdateExpressCompanyDto } from '@/server/modules/logistics/express-company.schema'

// 类型定义
type CreateRequest = InferRequestType<typeof expressCompanyClient.$post>['json']
type UpdateRequest = InferRequestType<typeof expressCompanyClient[':id']['$put']>['json']
type ExpressCompanyResponse = InferResponseType<typeof expressCompanyClient.$get, 200>['data'][0]

// 表单Schema直接使用后端定义
const createFormSchema = CreateExpressCompanyDto
const updateFormSchema = UpdateExpressCompanyDto

export const ExpressCompaniesPage = () => {
  const queryClient = useQueryClient()
  
  // 状态管理
  const [searchParams, setSearchParams] = useState({ page: 1, limit: 10, search: '' })
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [editingCompany, setEditingCompany] = useState<ExpressCompanyResponse | null>(null)
  const [isCreateForm, setIsCreateForm] = useState(true)
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false)
  const [companyToDelete, setCompanyToDelete] = useState<number | null>(null)

  // 表单实例
  const createForm = useForm<CreateRequest>({
    resolver: zodResolver(createFormSchema),
    defaultValues: {
      name: '',
      code: '',
      state: 1,
      sort: 100
    },
  })

  const updateForm = useForm<UpdateRequest>({
    resolver: zodResolver(updateFormSchema),
  })

  // 数据查询
  const { data, isLoading, refetch } = useQuery({
    queryKey: ['express-companies', searchParams],
    queryFn: async () => {
      const res = await expressCompanyClient.$get({
        query: {
          page: searchParams.page,
          pageSize: searchParams.limit,
          keyword: searchParams.search,
        }
      })
      if (res.status !== 200) throw new Error('获取快递公司列表失败')
      return await res.json()
    }
  })

  // 创建快递公司
  const createMutation = useMutation({
    mutationFn: async (data: CreateRequest) => {
      const res = await expressCompanyClient.$post({ json: data })
      if (res.status !== 201) throw new Error('创建快递公司失败')
      return await res.json()
    },
    onSuccess: () => {
      toast.success('快递公司创建成功')
      setIsModalOpen(false)
      queryClient.invalidateQueries({ queryKey: ['express-companies'] })
      createForm.reset()
    },
    onError: (error) => {
      toast.error(error instanceof Error ? error.message : '创建失败，请重试')
    }
  })

  // 更新快递公司
  const updateMutation = useMutation({
    mutationFn: async ({ id, data }: { id: number; data: UpdateRequest }) => {
      const res = await expressCompanyClient[':id']['$put']({
        param: { id: id.toString() },
        json: data
      })
      if (res.status !== 200) throw new Error('更新快递公司失败')
      return await res.json()
    },
    onSuccess: () => {
      toast.success('快递公司更新成功')
      setIsModalOpen(false)
      queryClient.invalidateQueries({ queryKey: ['express-companies'] })
    },
    onError: (error) => {
      toast.error(error instanceof Error ? error.message : '更新失败，请重试')
    }
  })

  // 删除快递公司
  const deleteMutation = useMutation({
    mutationFn: async (id: number) => {
      const res = await expressCompanyClient[':id']['$delete']({
        param: { id: id.toString() }
      })
      if (res.status !== 204) throw new Error('删除快递公司失败')
      return res
    },
    onSuccess: () => {
      toast.success('快递公司删除成功')
      setDeleteDialogOpen(false)
      queryClient.invalidateQueries({ queryKey: ['express-companies'] })
    },
    onError: (error) => {
      toast.error(error instanceof Error ? error.message : '删除失败，请重试')
    }
  })

  // 业务逻辑函数
  const handleSearch = () => {
    setSearchParams(prev => ({ ...prev, page: 1 }))
  }

  const handleCreateCompany = () => {
    setIsCreateForm(true)
    setEditingCompany(null)
    createForm.reset()
    setIsModalOpen(true)
  }

  const handleEditCompany = (company: ExpressCompanyResponse) => {
    setIsCreateForm(false)
    setEditingCompany(company)
    updateForm.reset({
      name: company.name,
      code: company.code,
      state: company.state,
      sort: company.sort || undefined
    })
    setIsModalOpen(true)
  }

  const handleDeleteCompany = (id: number) => {
    setCompanyToDelete(id)
    setDeleteDialogOpen(true)
  }

  const handleCreateSubmit = (data: CreateRequest) => {
    createMutation.mutate(data)
  }

  const handleUpdateSubmit = (data: UpdateRequest) => {
    if (editingCompany) {
      updateMutation.mutate({ id: editingCompany.id, data })
    }
  }

  const confirmDelete = () => {
    if (companyToDelete) {
      deleteMutation.mutate(companyToDelete)
    }
  }

  // 渲染页面
  if (isLoading) {
    return (
      <div className="space-y-4">
        <div className="flex justify-between items-center">
          <h1 className="text-2xl font-bold">快递公司管理</h1>
          <Button disabled>
            <Plus className="mr-2 h-4 w-4" />
            创建快递公司
          </Button>
        </div>
        
        <Card>
          <CardHeader>
            <Skeleton className="h-6 w-1/4" />
          </CardHeader>
          <CardContent>
            <div className="space-y-2">
              <Skeleton className="h-4 w-full" />
              <Skeleton className="h-4 w-full" />
              <Skeleton className="h-4 w-full" />
            </div>
          </CardContent>
        </Card>
      </div>
    )
  }

  return (
    <div className="space-y-4">
      {/* 页面标题区域 */}
      <div className="flex justify-between items-center">
        <h1 className="text-2xl font-bold">快递公司管理</h1>
        <Button onClick={handleCreateCompany}>
          <Plus className="mr-2 h-4 w-4" />
          创建快递公司
        </Button>
      </div>

      {/* 搜索区域 */}
      <Card>
        <CardHeader>
          <CardTitle>快递公司列表</CardTitle>
          <CardDescription>管理系统中的快递公司信息</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="mb-4">
            <form onSubmit={(e) => { e.preventDefault(); handleSearch() }} className="flex gap-2">
              <div className="relative flex-1 max-w-sm">
                <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
                <Input
                  placeholder="搜索快递公司名称或编号..."
                  value={searchParams.search}
                  onChange={(e) => setSearchParams(prev => ({ ...prev, search: e.target.value }))}
                  className="pl-8"
                />
              </div>
              <Button type="submit" variant="outline">
                搜索
              </Button>
            </form>
          </div>

          {/* 数据表格 */}
          <div className="rounded-md border">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>ID</TableHead>
                  <TableHead>公司名称</TableHead>
                  <TableHead>编号</TableHead>
                  <TableHead>状态</TableHead>
                  <TableHead>排序</TableHead>
                  <TableHead>创建时间</TableHead>
                  <TableHead className="text-right">操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {data?.data.map((company) => (
                  <TableRow key={company.id}>
                    <TableCell>{company.id}</TableCell>
                    <TableCell>{company.name}</TableCell>
                    <TableCell>{company.code}</TableCell>
                    <TableCell>
                      <Badge variant={company.state === 1 ? 'default' : 'secondary'}>
                        {company.state === 1 ? '启用' : '禁用'}
                      </Badge>
                    </TableCell>
                    <TableCell>{company.sort || '-'}</TableCell>
                    <TableCell>{new Date(company.createdAt).toLocaleDateString()}</TableCell>
                    <TableCell className="text-right">
                      <div className="flex justify-end gap-2">
                        <Button 
                          variant="ghost" 
                          size="icon" 
                          onClick={() => handleEditCompany(company)}
                          title="编辑"
                        >
                          <Edit className="h-4 w-4" />
                        </Button>
                        <Button 
                          variant="ghost" 
                          size="icon" 
                          onClick={() => handleDeleteCompany(company.id)}
                          title="删除"
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>

          {data?.data.length === 0 && !isLoading && (
            <div className="text-center py-8">
              <p className="text-muted-foreground">暂无快递公司数据</p>
            </div>
          )}

          <DataTablePagination
            currentPage={searchParams.page}
            pageSize={searchParams.limit}
            totalCount={data?.pagination.total || 0}
            onPageChange={(page, limit) => setSearchParams(prev => ({ ...prev, page, limit }))}
          />
        </CardContent>
      </Card>

      {/* 创建/编辑模态框 */}
      <Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
        <DialogContent className="sm:max-w-[500px] max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>{isCreateForm ? '创建快递公司' : '编辑快递公司'}</DialogTitle>
            <DialogDescription>
              {isCreateForm ? '创建一个新的快递公司' : '编辑现有快递公司信息'}
            </DialogDescription>
          </DialogHeader>
          
          {isCreateForm ? (
            <Form {...createForm}>
              <form onSubmit={createForm.handleSubmit(handleCreateSubmit)} className="space-y-4">
                <FormField
                  control={createForm.control}
                  name="name"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel className="flex items-center">
                        公司名称 <span className="text-red-500 ml-1">*</span>
                      </FormLabel>
                      <FormControl>
                        <Input placeholder="请输入快递公司名称" {...field} />
                      </FormControl>
                      <FormDescription>例如：顺丰速运、中通快递等</FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                
                <FormField
                  control={createForm.control}
                  name="code"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel className="flex items-center">
                        编号 <span className="text-red-500 ml-1">*</span>
                      </FormLabel>
                      <FormControl>
                        <Input placeholder="请输入快递公司编号" {...field} />
                      </FormControl>
                      <FormDescription>例如：SF、ZTO等唯一标识</FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                
                <FormField
                  control={createForm.control}
                  name="state"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>状态</FormLabel>
                      <FormControl>
                        <select 
                          className="w-full px-3 py-2 border rounded-md"
                          value={field.value}
                          onChange={(e) => field.onChange(parseInt(e.target.value))}
                        >
                          <option value={1}>启用</option>
                          <option value={2}>禁用</option>
                        </select>
                      </FormControl>
                      <FormDescription>选择快递公司的使用状态</FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                
                <FormField
                  control={createForm.control}
                  name="sort"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>排序</FormLabel>
                      <FormControl>
                        <Input 
                          type="number" 
                          placeholder="请输入排序值" 
                          {...field}
                          onChange={(e) => field.onChange(e.target.value ? parseInt(e.target.value) : null)}
                          value={field.value || ''}
                        />
                      </FormControl>
                      <FormDescription>数字越大优先级越高</FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                
                <DialogFooter>
                  <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>
                    取消
                  </Button>
                  <Button type="submit" disabled={createMutation.isPending}>
                    {createMutation.isPending ? '创建中...' : '创建'}
                  </Button>
                </DialogFooter>
              </form>
            </Form>
          ) : (
            <Form {...updateForm}>
              <form onSubmit={updateForm.handleSubmit(handleUpdateSubmit)} className="space-y-4">
                <FormField
                  control={updateForm.control}
                  name="name"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel className="flex items-center">
                        公司名称 <span className="text-red-500 ml-1">*</span>
                      </FormLabel>
                      <FormControl>
                        <Input placeholder="请输入快递公司名称" {...field} />
                      </FormControl>
                      <FormDescription>例如：顺丰速运、中通快递等</FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                
                <FormField
                  control={updateForm.control}
                  name="code"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel className="flex items-center">
                        编号 <span className="text-red-500 ml-1">*</span>
                      </FormLabel>
                      <FormControl>
                        <Input placeholder="请输入快递公司编号" {...field} />
                      </FormControl>
                      <FormDescription>例如：SF、ZTO等唯一标识</FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                
                <FormField
                  control={updateForm.control}
                  name="state"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>状态</FormLabel>
                      <FormControl>
                        <select 
                          className="w-full px-3 py-2 border rounded-md"
                          value={field.value}
                          onChange={(e) => field.onChange(parseInt(e.target.value))}
                        >
                          <option value={1}>启用</option>
                          <option value={2}>禁用</option>
                        </select>
                      </FormControl>
                      <FormDescription>选择快递公司的使用状态</FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                
                <FormField
                  control={updateForm.control}
                  name="sort"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>排序</FormLabel>
                      <FormControl>
                        <Input 
                          type="number" 
                          placeholder="请输入排序值" 
                          {...field}
                          onChange={(e) => field.onChange(e.target.value ? parseInt(e.target.value) : null)}
                          value={field.value || ''}
                        />
                      </FormControl>
                      <FormDescription>数字越大优先级越高</FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                
                <DialogFooter>
                  <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>
                    取消
                  </Button>
                  <Button type="submit" disabled={updateMutation.isPending}>
                    {updateMutation.isPending ? '更新中...' : '更新'}
                  </Button>
                </DialogFooter>
              </form>
            </Form>
          )}
        </DialogContent>
      </Dialog>

      {/* 删除确认对话框 */}
      <Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>确认删除</DialogTitle>
            <DialogDescription>
              确定要删除这个快递公司吗？此操作无法撤销。
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="outline" onClick={() => setDeleteDialogOpen(false)}>
              取消
            </Button>
            <Button variant="destructive" onClick={confirmDelete} disabled={deleteMutation.isPending}>
              {deleteMutation.isPending ? '删除中...' : '删除'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}

// 骨架屏组件
const Skeleton = ({ className }: { className?: string }) => (
  <div className={`animate-pulse rounded-md bg-muted ${className}`} />
)