import React, { useState, useEffect } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { toast } from 'sonner';
import { Layers, Package, Plus, Edit } from 'lucide-react';

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 { Badge } from '@d8d/shared-ui-components/components/ui/badge';
import { Separator } from '@d8d/shared-ui-components/components/ui/separator';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@d8d/shared-ui-components/components/ui/tabs';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@d8d/shared-ui-components/components/ui/dialog';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@d8d/shared-ui-components/components/ui/table';
import { goodsClientManager } from '../api/goodsClient';
import { BatchSpecCreatorInline } from './BatchSpecCreatorInline';
import { ChildGoodsList } from './ChildGoodsList';

interface GoodsParentChildPanelProps {
  // 基础属性
  mode: 'create' | 'edit';
  goodsId?: number;
  goodsName?: string;

  // 父子商品数据（双向绑定）
  spuId?: number;
  spuName?: string;
  childGoodsIds?: number[];
  batchSpecs?: BatchSpecTemplate[];

  // 回调函数
  onDataChange?: (data: ParentChildData) => void;
  onUpdate?: () => void;

  // 其他
  tenantId?: number;
  disabled?: boolean;
}

export interface ParentChildData {
  spuId: number;
  spuName: string | null;
  childGoodsIds: number[];
  batchSpecs?: BatchSpecTemplate[];
}

export interface BatchSpecTemplate {
  name: string;
  price: number;
  costPrice: number;
  stock: number;
  sort: number;
}

interface ChildGoods {
  id: number;
  name: string;
  price: number;
  costPrice: number;
  stock: number;
  sort: number;
  state: number;
  createdAt: string;
}

enum PanelMode {
  VIEW = 'view',
  BATCH_CREATE = 'batch',
  MANAGE_CHILDREN = 'manage'
}

export const GoodsParentChildPanel: React.FC<GoodsParentChildPanelProps> = ({
  mode,
  goodsId,
  goodsName,
  spuId = 0,
  spuName = null,
  childGoodsIds = [],
  batchSpecs = [],
  onDataChange,
  onUpdate,
  tenantId,
  disabled = false
}) => {
  const [panelMode, setPanelMode] = useState<PanelMode>(PanelMode.VIEW);
  const [selectedChildren, setSelectedChildren] = useState<number[]>(childGoodsIds);
  const [localBatchSpecs, setLocalBatchSpecs] = useState<BatchSpecTemplate[]>(batchSpecs);
  const [isSetAsParentDialogOpen, setIsSetAsParentDialogOpen] = useState(false);
  const [isRemoveParentDialogOpen, setIsRemoveParentDialogOpen] = useState(false);
  const [isDeleteChildDialogOpen, setIsDeleteChildDialogOpen] = useState(false);
  const [deletingChildId, setDeletingChildId] = useState<number | null>(null);
  const queryClient = useQueryClient();

  // 获取子商品列表（编辑模式）
  const { data: childrenData } = useQuery({
    queryKey: ['goods-children', goodsId, tenantId],
    queryFn: async () => {
      if (!goodsId || mode !== 'edit') return { data: [], total: 0 };

      try {
        const res = await goodsClientManager.get()[':id'].children.$get({
          param: { id: goodsId },
          query: { page: 1, pageSize: 100 }
        });

        if (res.status === 200) {
          const result = await res.json();
          return { data: result.data || [], total: result.total || 0 };
        }
        return { data: [], total: 0 };
      } catch (error) {
        console.error('获取子商品列表失败:', error);
        return { data: [], total: 0 };
      }
    },
    enabled: mode === 'edit' && !!goodsId
  });

  // 设为父商品Mutation
  const setAsParentMutation = useMutation({
    mutationFn: async () => {
      if (!goodsId) throw new Error('商品ID不能为空');
      const res = await goodsClientManager.get()[':id']['set-as-parent'].$post({
        param: { id: goodsId }
      });
      if (res.status !== 200) throw new Error('设为父商品失败');
      return await res.json();
    },
    onSuccess: () => {
      toast.success('已设为父商品');
      setIsSetAsParentDialogOpen(false);
      onUpdate?.();
      // 更新本地状态
      if (onDataChange) {
        onDataChange({
          spuId: 0,
          spuName: null,
          childGoodsIds: [],
          batchSpecs: localBatchSpecs
        });
      }
      // 使相关查询失效，保持缓存刷新逻辑一致
      if (goodsId) {
        queryClient.invalidateQueries({ queryKey: ['goods-children', goodsId, tenantId] });
      }
    },
    onError: (error) => {
      toast.error(error.message || '设为父商品失败');
    }
  });

  // 解除父子关系Mutation
  const removeParentMutation = useMutation({
    mutationFn: async () => {
      if (!goodsId) throw new Error('商品ID不能为空');
      const res = await goodsClientManager.get()[':id'].parent.$delete({
        param: { id: goodsId }
      });
      if (res.status !== 200) throw new Error('解除父子关系失败');
      return await res.json();
    },
    onSuccess: () => {
      toast.success('已解除父子关系');
      setIsRemoveParentDialogOpen(false);
      onUpdate?.();
      // 更新本地状态
      if (onDataChange) {
        onDataChange({
          spuId: 0,
          spuName: null,
          childGoodsIds: [],
          batchSpecs: localBatchSpecs
        });
      }
      // 使相关查询失效，保持缓存刷新逻辑一致
      if (goodsId) {
        queryClient.invalidateQueries({ queryKey: ['goods-children', goodsId, tenantId] });
      }
    },
    onError: (error) => {
      toast.error(error.message || '解除父子关系失败');
    }
  });

  // 删除子商品Mutation
  const deleteChildMutation = useMutation({
    mutationFn: async (childId: number) => {
      if (!childId) throw new Error('子商品ID不能为空');

      // 验证商品是子商品且在当前租户下
      try {
        // 获取商品详情验证spuId和tenantId
        const detailRes = await goodsClientManager.get()[':id'].$get({
          param: { id: childId }
        });
        if (detailRes.status !== 200) {
          throw new Error('获取商品详情失败');
        }
        const goodsDetail = await detailRes.json();

        // 验证必须是子商品
        if (!goodsDetail.spuId || goodsDetail.spuId <= 0) {
          throw new Error('只能删除子商品，该商品不是子商品');
        }

        // 验证租户匹配（如果提供了tenantId）
        if (tenantId && goodsDetail.tenantId !== tenantId) {
          throw new Error('租户不匹配，无权删除该商品');
        }
      } catch (error) {
        if (error instanceof Error) {
          throw error;
        }
        throw new Error('验证商品信息失败');
      }

      // 执行删除
      const res = await goodsClientManager.get()[':id'].$delete({
        param: { id: childId }
      });
      if (res.status !== 204) throw new Error('删除子商品失败');
      // 204 No Content 响应没有body，返回null
      return null;
    },
    onSuccess: () => {
      toast.success('子商品删除成功');
      setIsDeleteChildDialogOpen(false);
      setDeletingChildId(null);
      onUpdate?.();
      // 使子商品列表查询失效，强制刷新
      if (goodsId) {
        queryClient.invalidateQueries({ queryKey: ['goods-children', goodsId, tenantId] });
        queryClient.invalidateQueries({ queryKey: ['goods', 'children', 'list', goodsId, tenantId] });
      }
    },
    onError: (error) => {
      toast.error(error.message || '删除子商品失败');
    }
  });

  // 批量创建子商品Mutation
  const batchCreateChildrenMutation = useMutation({
    mutationFn: async (specs: BatchSpecTemplate[]) => {
      if (!goodsId) throw new Error('父商品ID不能为空');
      const res = await goodsClientManager.get().batchCreateChildren.$post({
        json: {
          parentGoodsId: goodsId,
          specs
        }
      });
      if (res.status !== 200) throw new Error('批量创建子商品失败');
      return await res.json();
    },
    onSuccess: () => {
      toast.success('批量创建子商品成功');
      setPanelMode(PanelMode.VIEW);
      setLocalBatchSpecs([]);
      onUpdate?.();

      // 使子商品列表查询失效，强制刷新
      if (goodsId) {
        queryClient.invalidateQueries({ queryKey: ['goods-children', goodsId, tenantId] });
        queryClient.invalidateQueries({ queryKey: ['goods', 'children', 'list', goodsId, tenantId] });
      }
    },
    onError: (error) => {
      toast.error(error.message || '批量创建子商品失败');
    }
  });

  // 初始化选中状态
  useEffect(() => {
    setSelectedChildren(childGoodsIds);
  }, [childGoodsIds]);

  // 数据变化时通知父组件
  useEffect(() => {
    if (onDataChange) {
      onDataChange({
        spuId,
        spuName,
        childGoodsIds: selectedChildren,
        batchSpecs: localBatchSpecs
      });
    }
  }, [spuId, spuName, selectedChildren, localBatchSpecs, onDataChange]);

  // 处理设为父商品
  const handleSetAsParent = () => {
    if (mode === 'create') {
      // 创建模式：直接更新本地状态
      if (onDataChange) {
        onDataChange({
          spuId: 0,
          spuName: null,
          childGoodsIds: [],
          batchSpecs: localBatchSpecs
        });
      }
      toast.success('已设为父商品');
    } else {
      // 编辑模式：调用API
      setIsSetAsParentDialogOpen(true);
    }
  };

  // 处理解除父子关系
  const handleRemoveParent = () => {
    if (mode === 'create') {
      // 创建模式：直接更新本地状态
      if (onDataChange) {
        onDataChange({
          spuId: 0,
          spuName: null,
          childGoodsIds: [],
          batchSpecs: localBatchSpecs
        });
      }
      toast.success('已解除父子关系');
    } else {
      // 编辑模式：调用API
      setIsRemoveParentDialogOpen(true);
    }
  };

  // 处理删除子商品
  const handleDeleteChild = (childId: number) => {
    setDeletingChildId(childId);
    setIsDeleteChildDialogOpen(true);
  };

  // 处理批量创建
  const handleBatchCreate = () => {
    if (localBatchSpecs.length === 0) {
      toast.error('请至少添加一个规格');
      return;
    }
    batchCreateChildrenMutation.mutate(localBatchSpecs);
  };

  // 判断当前商品状态
  const isParent = spuId === 0;
  const isChild = spuId > 0;
  const hasChildren = (childrenData?.total || 0) > 0 || selectedChildren.length > 0;

  return (
    <Card className="mt-6">
      <CardHeader>
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2">
            <Layers className="h-5 w-5 text-muted-foreground" />
            <CardTitle>父子商品管理</CardTitle>
          </div>
          <Badge variant={isParent ? "default" : isChild ? "secondary" : "outline"}>
            {isParent ? '父商品' : isChild ? '子商品' : '普通商品'}
          </Badge>
        </div>
        <CardDescription>
          {mode === 'create' ? '创建商品时配置父子关系' : '管理商品的父子关系'}
        </CardDescription>
      </CardHeader>

      <CardContent>
        <Tabs defaultValue="view" value={panelMode} onValueChange={(v) => {
          console.debug('Tabs onValueChange:', v, 'current panelMode:', panelMode);
          setPanelMode(v as PanelMode);
        }}>
          <TabsList className="grid w-full grid-cols-3">
            <TabsTrigger value="view">关系视图</TabsTrigger>
            <TabsTrigger value="batch" disabled={!isParent && mode === 'edit'}>
              批量创建
            </TabsTrigger>
            <TabsTrigger value="manage" disabled={mode === 'create'}>
              管理子商品
            </TabsTrigger>
          </TabsList>

          {/* 关系视图 */}
          <TabsContent value="view" className="space-y-4">
            <div className="rounded-lg border p-4">
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-3">
                  <Package className="h-5 w-5 text-muted-foreground" />
                  <div>
                    <h4 className="font-medium">{goodsName || '当前商品'}</h4>
                    <p className="text-sm text-muted-foreground">
                      {isParent ? '父商品' : isChild ? `子商品 (父商品: ${spuName})` : '普通商品'}
                    </p>
                  </div>
                </div>

                <div className="flex gap-2">
                  {!isParent && !isChild && (
                    <Button
                      size="sm"
                      onClick={handleSetAsParent}
                      disabled={disabled || setAsParentMutation.isPending}
                    >
                      {setAsParentMutation.isPending ? '处理中...' : '设为父商品'}
                    </Button>
                  )}

                  {isChild && (
                    <Button
                      size="sm"
                      variant="outline"
                      onClick={handleRemoveParent}
                      disabled={disabled || removeParentMutation.isPending}
                    >
                      {removeParentMutation.isPending ? '处理中...' : '解除关系'}
                    </Button>
                  )}
                </div>
              </div>

              {/* 子商品列表 */}
              {(hasChildren || (isParent && mode === 'edit')) && (
                <>
                  <Separator className="my-4" />
                  <div className="space-y-2">
                    <div className="flex items-center justify-between">
                      <h5 className="font-medium">子商品</h5>
                      <span className="text-sm text-muted-foreground">
                        {mode === 'edit' ? `${childrenData?.total || 0} 个子商品` : `${selectedChildren.length} 个已选择`}
                      </span>
                    </div>

                    {mode === 'edit' && childrenData?.data && childrenData.data.length > 0 ? (
                      <div className="rounded-md border">
                        <Table>
                          <TableHeader>
                            <TableRow>
                              <TableHead>名称</TableHead>
                              <TableHead>价格</TableHead>
                              <TableHead>库存</TableHead>
                              <TableHead>状态</TableHead>
                            </TableRow>
                          </TableHeader>
                          <TableBody>
                            {childrenData.data.map((child: ChildGoods) => (
                              <TableRow key={child.id}>
                                <TableCell className="font-medium">{child.name}</TableCell>
                                <TableCell>¥{child.price.toFixed(2)}</TableCell>
                                <TableCell>{child.stock}</TableCell>
                                <TableCell>
                                  <Badge variant={child.state === 1 ? "default" : "secondary"}>
                                    {child.state === 1 ? '可用' : '不可用'}
                                  </Badge>
                                </TableCell>
                              </TableRow>
                            ))}
                          </TableBody>
                        </Table>
                      </div>
                    ) : mode === 'create' && selectedChildren.length > 0 ? (
                      <div className="text-sm text-muted-foreground">
                        已选择 {selectedChildren.length} 个子商品
                      </div>
                    ) : (
                      <div className="text-sm text-muted-foreground italic">
                        暂无子商品
                      </div>
                    )}
                  </div>
                </>
              )}
            </div>

            {/* 操作按钮 */}
            <div className="flex gap-2">
              {isParent && (
                <Button
                  onClick={() => setPanelMode(PanelMode.BATCH_CREATE)}
                  disabled={disabled}
                >
                  <Plus className="mr-2 h-4 w-4" />
                  批量创建子商品
                </Button>
              )}

              {mode === 'edit' && (
                <Button
                  variant="outline"
                  onClick={() => setPanelMode(PanelMode.MANAGE_CHILDREN)}
                  disabled={disabled}
                >
                  <Edit className="mr-2 h-4 w-4" />
                  管理子商品
                </Button>
              )}
            </div>
          </TabsContent>

          {/* 批量创建 */}
          <TabsContent value="batch" className="space-y-4">
            <BatchSpecCreatorInline
              initialSpecs={localBatchSpecs}
              onSpecsChange={(newSpecs) => {
                setLocalBatchSpecs(newSpecs);
                if (onDataChange) {
                  onDataChange({
                    spuId,
                    spuName,
                    childGoodsIds: selectedChildren,
                    batchSpecs: newSpecs
                  });
                }
              }}
              onSaveTemplate={(templateName) => {
                toast.success(`模板 "${templateName}" 已保存`);
                // 在实际应用中，这里可以保存到本地存储或后端
              }}
              disabled={disabled}
            />

            {localBatchSpecs.length > 0 && (
              <div className="flex justify-end gap-2">
                <Button
                  variant="default"
                  onClick={handleBatchCreate}
                  disabled={disabled || batchCreateChildrenMutation.isPending}
                >
                  {batchCreateChildrenMutation.isPending ? '创建中...' : '批量创建子商品'}
                </Button>
                <Button
                  variant="outline"
                  onClick={() => setPanelMode(PanelMode.VIEW)}
                >
                  完成
                </Button>
              </div>
            )}
          </TabsContent>

          {/* 管理子商品 */}
          <TabsContent value="manage" className="space-y-4">
            <ChildGoodsList
              parentGoodsId={goodsId!}
              tenantId={tenantId}
              showActions={true}
              onDeleteChild={handleDeleteChild}
              deletingChildId={deletingChildId}
              isDeleting={deleteChildMutation.isPending}
            />

            <div className="flex justify-end">
              <Button
                variant="outline"
                onClick={() => setPanelMode(PanelMode.VIEW)}
              >
                返回
              </Button>
            </div>
          </TabsContent>
        </Tabs>
      </CardContent>

      {/* 设为父商品确认对话框 */}
      <Dialog open={isSetAsParentDialogOpen} onOpenChange={setIsSetAsParentDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>设为父商品</DialogTitle>
            <DialogDescription>
              确定要将"{goodsName}"设为父商品吗？设为父商品后，可以为其创建子商品规格。
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setIsSetAsParentDialogOpen(false)}
              disabled={setAsParentMutation.isPending}
            >
              取消
            </Button>
            <Button
              onClick={() => setAsParentMutation.mutate()}
              disabled={setAsParentMutation.isPending}
            >
              {setAsParentMutation.isPending ? '处理中...' : '确定'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 解除父子关系确认对话框 */}
      <Dialog open={isRemoveParentDialogOpen} onOpenChange={setIsRemoveParentDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>解除父子关系</DialogTitle>
            <DialogDescription>
              确定要解除"{goodsName}"与父商品"{spuName}"的关系吗？解除后，该商品将变为普通商品。
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setIsRemoveParentDialogOpen(false)}
              disabled={removeParentMutation.isPending}
            >
              取消
            </Button>
            <Button
              variant="destructive"
              onClick={() => removeParentMutation.mutate()}
              disabled={removeParentMutation.isPending}
            >
              {removeParentMutation.isPending ? '处理中...' : '确定'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 删除子商品确认对话框 */}
      <Dialog open={isDeleteChildDialogOpen} onOpenChange={setIsDeleteChildDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>删除子商品</DialogTitle>
            <DialogDescription>
              确定要永久删除这个子商品规格吗？此操作将删除商品实体，包括所有相关数据，无法恢复。
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setIsDeleteChildDialogOpen(false)}
              disabled={deleteChildMutation.isPending}
            >
              取消
            </Button>
            <Button
              variant="destructive"
              onClick={() => deletingChildId && deleteChildMutation.mutate(deletingChildId)}
              disabled={deleteChildMutation.isPending || !deletingChildId}
            >
              {deleteChildMutation.isPending ? '删除中...' : '确定删除'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </Card>
  );
};