import React, { useState } from 'react';
import { useQuery, useMutation } from '@tanstack/react-query';
import { Plus, Edit, Trash2, Search } from 'lucide-react';
import { format } from 'date-fns';
import { Input } from '@d8d/shared-ui-components/components/ui/input';
import { Textarea } from '@d8d/shared-ui-components/components/ui/textarea';
import { Button } from '@d8d/shared-ui-components/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@d8d/shared-ui-components/components/ui/card';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@d8d/shared-ui-components/components/ui/table';
import { Skeleton } from '@d8d/shared-ui-components/components/ui/skeleton';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@d8d/shared-ui-components/components/ui/dialog';
import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from '@d8d/shared-ui-components/components/ui/form';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { toast } from 'sonner';
import { DataTablePagination } from '@d8d/shared-ui-components/components/admin/DataTablePagination';
import { systemConfigClientManager } from '../api/systemConfigClient';
import { CreateSystemConfigSchema, UpdateSystemConfigSchema } from '@d8d/core-module-mt/system-config-module-mt/schemas';
import type { SystemConfigFormData, SystemConfigSearchParams, CreateSystemConfigRequest, UpdateSystemConfigRequest, SystemConfigResponse } from '../types';

type CreateRequest = CreateSystemConfigRequest;
type UpdateRequest = UpdateSystemConfigRequest;

const createFormSchema = CreateSystemConfigSchema;
const updateFormSchema = UpdateSystemConfigSchema;

export const SystemConfigManagement: React.FC = () => {
  const [searchParams, setSearchParams] = useState<SystemConfigSearchParams>({ page: 1, limit: 10, search: '' });
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingSystemConfig, setEditingSystemConfig] = useState<SystemConfigResponse | null>(null);
  const [isCreateForm, setIsCreateForm] = useState(true);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [systemConfigToDelete, setSystemConfigToDelete] = useState<number | null>(null);

  // 表单实例
  const createForm = useForm({
    resolver: zodResolver(createFormSchema),
    defaultValues: {
      configKey: '',
      configValue: '',
      description: ''
    }
  });

  const updateForm = useForm({
    resolver: zodResolver(updateFormSchema),
    defaultValues: {}
  });

  // 数据查询
  const { data, isLoading, refetch } = useQuery({
    queryKey: ['system-configs', searchParams],
    queryFn: async () => {
      const res = await systemConfigClientManager.get().index.$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 systemConfigClientManager.get().index.$post({ json: data });
      if (res.status !== 201) throw new Error('创建系统配置失败');
      return await res.json();
    },
    onSuccess: () => {
      toast.success('系统配置创建成功');
      setIsModalOpen(false);
      createForm.reset();
      refetch();
    },
    onError: (error) => {
      toast.error(error instanceof Error ? error.message : '创建系统配置失败');
    }
  });

  // 更新系统配置
  const updateMutation = useMutation({
    mutationFn: async ({ id, data }: { id: number; data: UpdateRequest }) => {
      const res = await systemConfigClientManager.get()[':id']['$put']({
        param: { id },
        json: data
      });
      if (res.status !== 200) throw new Error('更新系统配置失败');
      return await res.json();
    },
    onSuccess: () => {
      toast.success('系统配置更新成功');
      setIsModalOpen(false);
      setEditingSystemConfig(null);
      refetch();
    },
    onError: (error) => {
      toast.error(error instanceof Error ? error.message : '更新系统配置失败');
    }
  });

  // 删除系统配置
  const deleteMutation = useMutation({
    mutationFn: async (id: number) => {
      const res = await systemConfigClientManager.get()[':id']['$delete']({
        param: { id }
      });
      if (res.status !== 204) throw new Error('删除系统配置失败');
      return await res.json();
    },
    onSuccess: () => {
      toast.success('系统配置删除成功');
      setDeleteDialogOpen(false);
      setSystemConfigToDelete(null);
      refetch();
    },
    onError: (error) => {
      toast.error(error instanceof Error ? error.message : '删除系统配置失败');
    }
  });

  // 处理搜索
  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    setSearchParams((prev: SystemConfigSearchParams) => ({ ...prev, page: 1 }));
    refetch();
  };

  // 处理创建系统配置
  const handleCreateSystemConfig = () => {
    setIsCreateForm(true);
    setEditingSystemConfig(null);
    createForm.reset();
    setIsModalOpen(true);
  };

  // 处理编辑系统配置
  const handleEditSystemConfig = (systemConfig: SystemConfigResponse) => {
    setIsCreateForm(false);
    setEditingSystemConfig(systemConfig);
    updateForm.reset({
      configKey: systemConfig.configKey || undefined,
      configValue: systemConfig.configValue || undefined,
      description: systemConfig.description || undefined
    });
    setIsModalOpen(true);
  };

  // 处理删除系统配置
  const handleDeleteSystemConfig = (id: number) => {
    setSystemConfigToDelete(id);
    setDeleteDialogOpen(true);
  };

  // 确认删除
  const confirmDelete = () => {
    if (systemConfigToDelete) {
      deleteMutation.mutate(systemConfigToDelete);
    }
  };

  // 处理创建表单提交
  const handleCreateSubmit = async (data: SystemConfigFormData) => {
    try {
      await createMutation.mutateAsync(data);
    } catch (error) {
      throw error;
    }
  };

  // 处理编辑表单提交
  const handleUpdateSubmit = async (data: any) => {
    if (!editingSystemConfig) return;

    try {
      await updateMutation.mutateAsync({
        id: editingSystemConfig.id,
        data
      });
    } catch (error) {
      throw error;
    }
  };

  return (
    <div className="space-y-4">
      <div className="flex justify-between items-center">
        <h1 className="text-2xl font-bold">系统配置管理</h1>
        <Button onClick={handleCreateSystemConfig}>
          <Plus className="mr-2 h-4 w-4" />
          创建配置
        </Button>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>系统配置列表</CardTitle>
          <CardDescription>管理系统所有配置项，包括小程序配置、支付参数等</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="mb-4">
            <form onSubmit={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: SystemConfigSearchParams) => ({ ...prev, search: e.target.value }))}
                  className="pl-8"
                  data-testid="search-input"
                />
              </div>
              <Button type="submit" variant="outline">
                搜索
              </Button>
            </form>
          </div>

          <div className="rounded-md border">
            <div className="relative w-full overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>ID</TableHead>
                    <TableHead>配置键</TableHead>
                    <TableHead>配置值</TableHead>
                    <TableHead>描述</TableHead>
                    <TableHead>创建时间</TableHead>
                    <TableHead>更新时间</TableHead>
                    <TableHead className="text-right">操作</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {isLoading ? (
                    Array.from({ length: 5 }).map((_, index) => (
                      <TableRow key={index}>
                        <TableCell>
                          <Skeleton className="h-4 w-8" />
                        </TableCell>
                        <TableCell>
                          <Skeleton className="h-4 w-12" />
                        </TableCell>
                        <TableCell>
                          <Skeleton className="h-4 w-32" />
                        </TableCell>
                        <TableCell>
                          <Skeleton className="h-4 w-40" />
                        </TableCell>
                        <TableCell>
                          <Skeleton className="h-4 w-24" />
                        </TableCell>
                        <TableCell>
                          <Skeleton className="h-4 w-24" />
                        </TableCell>
                        <TableCell>
                          <Skeleton className="h-4 w-24" />
                        </TableCell>
                        <TableCell>
                          <div className="flex justify-end gap-2">
                            <Skeleton className="h-8 w-8 rounded" />
                            <Skeleton className="h-8 w-8 rounded" />
                          </div>
                        </TableCell>
                      </TableRow>
                    ))
                  ) : data?.data && data.data.length > 0 ? (
                    data.data.map((systemConfig) => (
                      <TableRow key={systemConfig.id}>
                        <TableCell>{systemConfig.id}</TableCell>
                        <TableCell>
                          <code className="text-xs bg-muted px-1 rounded">{systemConfig.configKey}</code>
                        </TableCell>
                        <TableCell>
                          <div className="max-w-xs truncate">
                            {systemConfig.configValue}
                          </div>
                        </TableCell>
                        <TableCell>
                          {systemConfig.description || '-'}
                        </TableCell>
                        <TableCell>
                          {systemConfig.createdAt ? format(new Date(systemConfig.createdAt), 'yyyy-MM-dd HH:mm') : '-'}
                        </TableCell>
                        <TableCell>
                          {systemConfig.updatedAt ? format(new Date(systemConfig.updatedAt), 'yyyy-MM-dd HH:mm') : '-'}
                        </TableCell>
                        <TableCell className="text-right">
                          <div className="flex justify-end gap-2">
                            <Button
                              variant="ghost"
                              size="icon"
                              onClick={() => handleEditSystemConfig(systemConfig)}
                              data-testid={`edit-button-${systemConfig.id}`}
                            >
                              <Edit className="h-4 w-4" />
                            </Button>
                            <Button
                              variant="ghost"
                              size="icon"
                              onClick={() => handleDeleteSystemConfig(systemConfig.id)}
                              data-testid={`delete-button-${systemConfig.id}`}
                            >
                              <Trash2 className="h-4 w-4" />
                            </Button>
                          </div>
                        </TableCell>
                      </TableRow>
                    ))
                  ) : (
                    <TableRow>
                      <TableCell colSpan={8} className="text-center py-8">
                        <p className="text-muted-foreground">暂无系统配置数据</p>
                      </TableCell>
                    </TableRow>
                  )}
                </TableBody>
              </Table>
            </div>
          </div>

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

      {/* 创建/编辑对话框 */}
      <Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
        <DialogContent className="sm:max-w-[600px] 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="configKey"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel className="flex items-center">
                        配置键 <span className="text-red-500 ml-1">*</span>
                      </FormLabel>
                      <FormControl>
                        <Input
                          placeholder="请输入配置键，如：app.login.enabled"
                          {...field}
                          data-testid="config-key-input"
                        />
                      </FormControl>
                      <FormDescription>配置项的唯一标识，使用点分隔符命名，如：app.login.enabled</FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={createForm.control}
                  name="configValue"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel className="flex items-center">
                        配置值 <span className="text-red-500 ml-1">*</span>
                      </FormLabel>
                      <FormControl>
                        <Textarea
                          placeholder="请输入配置值"
                          {...field}
                          data-testid="config-value-input"
                        />
                      </FormControl>
                      <FormDescription>配置项的具体值，可以是字符串、数字或布尔值</FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={createForm.control}
                  name="description"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>配置描述</FormLabel>
                      <FormControl>
                        <Textarea
                          placeholder="请输入配置描述"
                          {...field}
                          data-testid="description-input"
                        />
                      </FormControl>
                      <FormDescription>配置项的详细说明和用途描述</FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <DialogFooter>
                  <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>
                    取消
                  </Button>
                  <Button type="submit" disabled={createMutation.isPending} data-testid="create-submit-button">
                    创建
                  </Button>
                </DialogFooter>
              </form>
            </Form>
          ) : (
            // 编辑表单（独立渲染）
            <Form {...updateForm}>
              <form onSubmit={updateForm.handleSubmit(handleUpdateSubmit)} className="space-y-4">
                <FormField
                  control={updateForm.control}
                  name="configKey"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel className="flex items-center">
                        配置键 <span className="text-red-500 ml-1">*</span>
                      </FormLabel>
                      <FormControl>
                        <Input
                          placeholder="请输入配置键"
                          {...field}
                          data-testid="config-key-input"
                        />
                      </FormControl>
                      <FormDescription>配置项的唯一标识，使用点分隔符命名</FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={updateForm.control}
                  name="configValue"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel className="flex items-center">
                        配置值 <span className="text-red-500 ml-1">*</span>
                      </FormLabel>
                      <FormControl>
                        <Textarea
                          placeholder="请输入配置值"
                          {...field}
                          data-testid="config-value-input"
                        />
                      </FormControl>
                      <FormDescription>配置项的具体值，可以是字符串、数字或布尔值</FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={updateForm.control}
                  name="description"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>配置描述</FormLabel>
                      <FormControl>
                        <Textarea
                          placeholder="请输入配置描述"
                          {...field}
                          data-testid="description-input"
                        />
                      </FormControl>
                      <FormDescription>配置项的详细说明和用途描述</FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <DialogFooter>
                  <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>
                    取消
                  </Button>
                  <Button type="submit" disabled={updateMutation.isPending} data-testid="update-submit-button">
                    更新
                  </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}
              data-testid="confirm-delete-button"
            >
              {deleteMutation.isPending ? '删除中...' : '删除'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
};

export default SystemConfigManagement;