import React from 'react';
import { useQuery } from '@tanstack/react-query';
import { Package, ChevronRight, ChevronDown, Link, Unlink } from 'lucide-react';

import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@d8d/shared-ui-components/components/ui/card';
import { Button } from '@d8d/shared-ui-components/components/ui/button';
import { Badge } from '@d8d/shared-ui-components/components/ui/badge';
import { Skeleton } from '@d8d/shared-ui-components/components/ui/skeleton';
import { goodsClientManager } from '../api/goodsClient';

interface GoodsRelationshipTreeProps {
  goodsId: number;
  tenantId?: number;
}

interface GoodsNode {
  id: number;
  name: string;
  price: number;
  stock: number;
  spuId: number;
  spuName: string | null;
  state: number;
  childGoods?: GoodsNode[];
  parentGoods?: GoodsNode | null;
}

export const GoodsRelationshipTree: React.FC<GoodsRelationshipTreeProps> = ({
  goodsId,
  tenantId
}) => {
  const [expandedNodes, setExpandedNodes] = React.useState<Set<number>>(new Set([goodsId]));

  // 获取商品详情
  const { data: goodsData, isLoading } = useQuery({
    queryKey: ['goods', 'relationship', goodsId, tenantId],
    queryFn: async () => {
      const res = await goodsClientManager.get()[':id']['$get']({
        param: { id: goodsId }
      });
      if (res.status !== 200) throw new Error('获取商品详情失败');
      return await res.json();
    }
  });

  // 获取子商品列表
  const { data: childrenData, isLoading: isLoadingChildren } = useQuery({
    queryKey: ['goods', 'children', goodsId, tenantId],
    queryFn: async () => {
      // 这里需要后端API支持查询子商品
      // 暂时使用商品列表API过滤spuId
      const res = await goodsClientManager.get().index.$get({
        query: {
          page: 1,
          pageSize: 100,
          spuId: goodsId,
          tenantId: tenantId
        }
      });
      if (res.status !== 200) throw new Error('获取子商品列表失败');
      const result = await res.json();
      return result.data || [];
    },
    enabled: !!goodsData && goodsData.spuId === 0 // 只有父商品才查询子商品
  });

  // 获取父商品信息（如果是子商品）
  const { data: parentData, isLoading: isLoadingParent } = useQuery({
    queryKey: ['goods', 'parent', goodsData?.spuId, tenantId],
    queryFn: async () => {
      if (!goodsData?.spuId || goodsData.spuId === 0) return null;

      const res = await goodsClientManager.get()[':id']['$get']({
        param: { id: goodsData.spuId }
      });
      if (res.status !== 200) throw new Error('获取父商品信息失败');
      return await res.json();
    },
    enabled: !!goodsData && goodsData.spuId > 0
  });

  const toggleNode = (nodeId: number) => {
    const newExpanded = new Set(expandedNodes);
    if (newExpanded.has(nodeId)) {
      newExpanded.delete(nodeId);
    } else {
      newExpanded.add(nodeId);
    }
    setExpandedNodes(newExpanded);
  };

  const renderGoodsNode = (goods: GoodsNode, level: number = 0, isChild: boolean = false) => {
    const hasChildren = goods.childGoods && goods.childGoods.length > 0;
    const isExpanded = expandedNodes.has(goods.id);
    const isParent = goods.spuId === 0;

    return (
      <div key={goods.id} className="space-y-2">
        <div
          className={`flex items-center gap-2 p-2 rounded-md hover:bg-accent ${isChild ? 'ml-6' : ''}`}
          style={{ marginLeft: `${level * 24}px` }}
        >
          {hasChildren && (
            <Button
              variant="ghost"
              size="icon"
              className="h-6 w-6"
              onClick={() => toggleNode(goods.id)}
            >
              {isExpanded ? (
                <ChevronDown className="h-4 w-4" />
              ) : (
                <ChevronRight className="h-4 w-4" />
              )}
            </Button>
          )}
          {!hasChildren && <div className="w-6" />}

          <div className="flex items-center gap-2">
            <Package className="h-4 w-4 text-muted-foreground" />
            <span className="font-medium">{goods.name}</span>
            <Badge variant={isParent ? "default" : "secondary"}>
              {isParent ? '父商品' : '子商品'}
            </Badge>
            <Badge variant={goods.state === 1 ? "default" : "secondary"}>
              {goods.state === 1 ? '可用' : '不可用'}
            </Badge>
          </div>

          <div className="ml-auto flex items-center gap-4 text-sm text-muted-foreground">
            <span>¥{goods.price.toFixed(2)}</span>
            <span>库存: {goods.stock}</span>
            {!isParent && goods.spuName && (
              <span className="flex items-center gap-1">
                <Link className="h-3 w-3" />
                父商品: {goods.spuName}
              </span>
            )}
          </div>
        </div>

        {isExpanded && hasChildren && goods.childGoods && (
          <div className="space-y-2">
            {goods.childGoods.map(child => renderGoodsNode(child, level + 1, true))}
          </div>
        )}
      </div>
    );
  };

  const buildRelationshipTree = (): GoodsNode | null => {
    if (!goodsData) return null;

    const root: GoodsNode = {
      id: goodsData.id,
      name: goodsData.name,
      price: goodsData.price,
      stock: goodsData.stock,
      spuId: goodsData.spuId,
      spuName: goodsData.spuName,
      state: goodsData.state,
      childGoods: childrenData || []
    };

    // 如果是子商品，添加父商品信息
    if (parentData) {
      root.parentGoods = {
        id: parentData.id,
        name: parentData.name,
        price: parentData.price,
        stock: parentData.stock,
        spuId: parentData.spuId,
        spuName: parentData.spuName,
        state: parentData.state
      };
    }

    return root;
  };

  const relationshipTree = buildRelationshipTree();

  if (isLoading || isLoadingChildren || isLoadingParent) {
    return (
      <Card>
        <CardHeader>
          <CardTitle>商品关系树</CardTitle>
          <CardDescription>加载中...</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="space-y-2">
            <Skeleton className="h-12 w-full" />
            <Skeleton className="h-12 w-full" />
            <Skeleton className="h-12 w-full" />
          </div>
        </CardContent>
      </Card>
    );
  }

  if (!relationshipTree) {
    return (
      <Card>
        <CardHeader>
          <CardTitle>商品关系树</CardTitle>
          <CardDescription>未找到商品信息</CardDescription>
        </CardHeader>
        <CardContent>
          <p className="text-muted-foreground">无法加载商品关系信息</p>
        </CardContent>
      </Card>
    );
  }

  const isParent = relationshipTree.spuId === 0;
  const hasChildren = relationshipTree.childGoods && relationshipTree.childGoods.length > 0;
  const hasParent = relationshipTree.parentGoods;

  return (
    <Card>
      <CardHeader>
        <CardTitle>商品关系树</CardTitle>
        <CardDescription>
          {isParent ? '父商品及其子商品关系' : '子商品及其父商品关系'}
        </CardDescription>
      </CardHeader>
      <CardContent>
        <div className="space-y-4">
          {/* 父商品信息（如果是子商品） */}
          {hasParent && relationshipTree.parentGoods && (
            <div className="mb-4 p-4 border rounded-lg bg-muted/50">
              <div className="flex items-center gap-2 mb-2">
                <Unlink className="h-4 w-4" />
                <h3 className="font-semibold">父商品</h3>
              </div>
              {renderGoodsNode(relationshipTree.parentGoods, 0, false)}
            </div>
          )}

          {/* 当前商品 */}
          <div className={`p-4 border rounded-lg ${isParent ? 'bg-primary/5' : 'bg-secondary/50'}`}>
            <div className="flex items-center gap-2 mb-2">
              <Package className="h-4 w-4" />
              <h3 className="font-semibold">当前商品</h3>
              <Badge variant={isParent ? "default" : "secondary"}>
                {isParent ? '父商品' : '子商品'}
              </Badge>
            </div>
            {renderGoodsNode(relationshipTree, 0, false)}
          </div>

          {/* 子商品列表（如果是父商品） */}
          {isParent && hasChildren && (
            <div className="mt-4 p-4 border rounded-lg">
              <div className="flex items-center gap-2 mb-2">
                <Link className="h-4 w-4" />
                <h3 className="font-semibold">子商品 ({relationshipTree.childGoods?.length || 0})</h3>
              </div>
              <div className="space-y-2">
                {relationshipTree.childGoods?.map(child => renderGoodsNode(child, 0, true))}
              </div>
            </div>
          )}

          {/* 空状态 */}
          {isParent && !hasChildren && (
            <div className="text-center py-8 text-muted-foreground">
              <Package className="h-12 w-12 mx-auto mb-2 opacity-50" />
              <p>此商品没有子商品</p>
              <p className="text-sm">可以点击"批量创建子商品"按钮添加子商品规格</p>
            </div>
          )}

          {/* 关系说明 */}
          <div className="mt-4 text-sm text-muted-foreground space-y-1">
            <p className="flex items-center gap-2">
              <Badge variant="default" className="h-4 px-1">父商品</Badge>
              <span>spuId = 0，可以有多个子商品</span>
            </p>
            <p className="flex items-center gap-2">
              <Badge variant="secondary" className="h-4 px-1">子商品</Badge>
              <span>spuId &gt; 0，关联到父商品，表示不同规格</span>
            </p>
            <p>• 父子商品必须在同一租户下</p>
            <p>• 子商品不能有自己的子商品</p>
            <p>• 一个商品不能同时是父商品和子商品</p>
          </div>
        </div>
      </CardContent>
    </Card>
  );
};