import React, { useState, useEffect } from 'react';
import { useMutation, useQuery } from '@tanstack/react-query';
import { Plus, Trash2, Check, X, Loader2 } from 'lucide-react';
import { toast } from 'sonner';

import { Button } from '@d8d/shared-ui-components/components/ui/button';
import { Input } from '@d8d/shared-ui-components/components/ui/input';
import { Label } from '@d8d/shared-ui-components/components/ui/label';
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 { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@d8d/shared-ui-components/components/ui/dialog';
import { goodsClientManager } from '../api/goodsClient';

interface BatchSpecCreatorProps {
  parentGoodsId: number;
  parentGoodsName: string;
  tenantId?: number;
  onSuccess?: () => void;
  onCancel?: () => void;
}

interface SpecItem {
  id: number;
  name: string;
  price: number;
  costPrice: number;
  stock: number;
  sort: number;
}

export const BatchSpecCreator: React.FC<BatchSpecCreatorProps> = ({
  parentGoodsId,
  parentGoodsName,
  tenantId,
  onSuccess,
  onCancel
}) => {
  const [specs, setSpecs] = useState<SpecItem[]>([
    { id: 1, name: '', price: 0, costPrice: 0, stock: 0, sort: 1 },
    { id: 2, name: '', price: 0, costPrice: 0, stock: 0, sort: 2 },
  ]);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [parentCategoryId1, setParentCategoryId1] = useState<number>(0);
  const [parentCategoryId2, setParentCategoryId2] = useState<number>(0);
  const [parentCategoryId3, setParentCategoryId3] = useState<number>(0);
  const [parentGoodsType, setParentGoodsType] = useState<number>(1);
  const [parentSupplierId, setParentSupplierId] = useState<number | null>(null);
  const [parentMerchantId, setParentMerchantId] = useState<number | null>(null);

  // 获取父商品详情
  const { data: parentGoodsData, isLoading: isLoadingParentGoods } = useQuery({
    queryKey: ['parentGoods', parentGoodsId],
    queryFn: async () => {
      const res = await goodsClientManager.get()[':id']['$get']({
        param: { id: parentGoodsId }
      });
      if (res.status !== 200) throw new Error('获取父商品信息失败');
      return await res.json();
    },
    onSuccess: (data) => {

      // 尝试多种可能的字段名
      const catId1 = data.categoryId1 ?? (data as any).category_id1 ?? 0;
      const catId2 = data.categoryId2 ?? (data as any).category_id2 ?? 0;
      const catId3 = data.categoryId3 ?? (data as any).category_id3 ?? 0;


      // 设置父商品的分类信息
      setParentCategoryId1(catId1);
      setParentCategoryId2(catId2);
      setParentCategoryId3(catId3);
      setParentGoodsType(data.goodsType || 1);
      setParentSupplierId(data.supplierId || null);
      setParentMerchantId(data.merchantId || null);
    },
    onError: (error) => {
      toast.error(error.message || '获取父商品信息失败');
    }
  });

  // 批量创建子商品
  const batchCreateMutation = useMutation({
    mutationFn: async (specsData: SpecItem[]) => {
      const promises = specsData.map(spec => {
        return goodsClientManager.get().index.$post({
          json: {
            name: `${parentGoodsName} - ${spec.name}`,
            price: spec.price,
            costPrice: spec.costPrice,
            stock: spec.stock,
            sort: spec.sort,
            spuId: parentGoodsId,
            spuName: parentGoodsName,
            categoryId1: parentCategoryId1,
            categoryId2: parentCategoryId2,
            categoryId3: parentCategoryId3,
            goodsType: parentGoodsType,
            supplierId: parentSupplierId,
            merchantId: parentMerchantId,
            imageFileId: null,
            slideImageIds: [],
            detail: '',
            instructions: '',
            state: 1,
            lowestBuy: 1
          }
        });
      });

      const results = await Promise.all(promises);
      return results;
    },
    onSuccess: () => {
      toast.success('批量创建子商品成功');
      setIsSubmitting(false);
      if (onSuccess) onSuccess();
    },
    onError: (error) => {
      toast.error(error.message || '批量创建子商品失败');
      setIsSubmitting(false);
    }
  });

  const addSpec = () => {
    const newId = specs.length > 0 ? Math.max(...specs.map(s => s.id)) + 1 : 1;
    setSpecs([...specs, {
      id: newId,
      name: '',
      price: 0,
      costPrice: 0,
      stock: 0,
      sort: newId
    }]);
  };

  const removeSpec = (id: number) => {
    if (specs.length <= 1) {
      toast.error('至少需要保留一个规格');
      return;
    }
    setSpecs(specs.filter(spec => spec.id !== id));
  };

  const updateSpec = (id: number, field: keyof SpecItem, value: string | number) => {
    setSpecs(specs.map(spec => {
      if (spec.id === id) {
        return { ...spec, [field]: value };
      }
      return spec;
    }));
  };

  const validateSpecs = (): boolean => {
    // 检查规格名称不能为空
    for (const spec of specs) {
      if (!spec.name.trim()) {
        toast.error(`规格 ${spec.id} 的名称不能为空`);
        return false;
      }
      if (spec.price < 0) {
        toast.error(`规格 ${spec.name} 的价格不能为负数`);
        return false;
      }
      if (spec.costPrice < 0) {
        toast.error(`规格 ${spec.name} 的成本价不能为负数`);
        return false;
      }
      if (spec.stock < 0) {
        toast.error(`规格 ${spec.name} 的库存不能为负数`);
        return false;
      }
    }

    // 检查规格名称不能重复
    const names = specs.map(s => s.name.trim().toLowerCase());
    const uniqueNames = new Set(names);
    if (uniqueNames.size !== names.length) {
      toast.error('规格名称不能重复');
      return false;
    }

    return true;
  };

  const handleSubmit = async () => {
    if (!validateSpecs()) {
      return;
    }

    setIsSubmitting(true);
    try {
      await batchCreateMutation.mutateAsync(specs);
    } catch (error) {
      // 错误已经在mutation中处理
    }
  };

  const handleCancel = () => {
    if (onCancel) onCancel();
  };

  if (isLoadingParentGoods) {
    return (
      <Dialog open={true} onOpenChange={(open) => !open && handleCancel()}>
        <DialogContent className="sm:max-w-[900px] max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>批量创建子商品规格</DialogTitle>
            <DialogDescription>
              为父商品 "{parentGoodsName}" 批量创建多个子商品规格
            </DialogDescription>
          </DialogHeader>
          <div className="flex items-center justify-center py-12">
            <div className="text-center">
              <Loader2 className="h-8 w-8 animate-spin mx-auto mb-4 text-muted-foreground" />
              <p className="text-muted-foreground">正在加载父商品信息...</p>
            </div>
          </div>
          <DialogFooter>
            <Button
              type="button"
              variant="outline"
              onClick={handleCancel}
              disabled={true}
            >
              <X className="mr-2 h-4 w-4" />
              取消
            </Button>
            <Button
              type="button"
              disabled={true}
            >
              <Check className="mr-2 h-4 w-4" />
              加载中...
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    );
  }

  return (
    <Dialog open={true} onOpenChange={(open) => !open && handleCancel()}>
      <DialogContent className="sm:max-w-[900px] max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>批量创建子商品规格</DialogTitle>
          <DialogDescription>
            为父商品 "{parentGoodsName}" 批量创建多个子商品规格
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle>父商品信息</CardTitle>
              <CardDescription>基于此父商品创建子商品规格</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>父商品ID</Label>
                  <Input value={parentGoodsId} disabled />
                </div>
                <div>
                  <Label>父商品名称</Label>
                  <Input value={parentGoodsName} disabled />
                </div>
                <div>
                  <Label>一级分类ID</Label>
                  <Input value={parentCategoryId1} disabled />
                </div>
                <div>
                  <Label>二级分类ID</Label>
                  <Input value={parentCategoryId2} disabled />
                </div>
                <div>
                  <Label>三级分类ID</Label>
                  <Input value={parentCategoryId3} disabled />
                </div>
                <div>
                  <Label>商品类型</Label>
                  <Input value={parentGoodsType === 1 ? '实物产品' : '虚拟产品'} disabled />
                </div>
              </div>
              <div className="mt-4 text-sm text-muted-foreground">
                <p>子商品将继承父商品的分类信息、商品类型、供应商和商户信息</p>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="flex flex-row items-center justify-between">
              <div>
                <CardTitle>规格列表</CardTitle>
                <CardDescription>输入每个子商品规格的详细信息</CardDescription>
              </div>
              <Button type="button" onClick={addSpec} size="sm">
                <Plus className="mr-2 h-4 w-4" />
                添加规格
              </Button>
            </CardHeader>
            <CardContent>
              <div className="rounded-md border">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead className="w-[200px]">规格名称</TableHead>
                      <TableHead>售卖价</TableHead>
                      <TableHead>成本价</TableHead>
                      <TableHead>库存</TableHead>
                      <TableHead className="w-[100px]">排序</TableHead>
                      <TableHead className="w-[80px] text-right">操作</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {specs.map((spec) => (
                      <TableRow key={spec.id}>
                        <TableCell>
                          <Input
                            value={spec.name}
                            onChange={(e) => updateSpec(spec.id, 'name', e.target.value)}
                            placeholder="例如：红色、64GB、大号"
                          />
                        </TableCell>
                        <TableCell>
                          <Input
                            type="number"
                            step="0.01"
                            value={spec.price}
                            onChange={(e) => updateSpec(spec.id, 'price', parseFloat(e.target.value) || 0)}
                            placeholder="0.00"
                          />
                        </TableCell>
                        <TableCell>
                          <Input
                            type="number"
                            step="0.01"
                            value={spec.costPrice}
                            onChange={(e) => updateSpec(spec.id, 'costPrice', parseFloat(e.target.value) || 0)}
                            placeholder="0.00"
                          />
                        </TableCell>
                        <TableCell>
                          <Input
                            type="number"
                            value={spec.stock}
                            onChange={(e) => updateSpec(spec.id, 'stock', parseInt(e.target.value) || 0)}
                            placeholder="0"
                          />
                        </TableCell>
                        <TableCell>
                          <Input
                            type="number"
                            value={spec.sort}
                            onChange={(e) => updateSpec(spec.id, 'sort', parseInt(e.target.value) || 0)}
                          />
                        </TableCell>
                        <TableCell className="text-right">
                          <Button
                            type="button"
                            variant="ghost"
                            size="icon"
                            onClick={() => removeSpec(spec.id)}
                            disabled={specs.length <= 1}
                          >
                            <Trash2 className="h-4 w-4" />
                          </Button>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>

              <div className="mt-4 text-sm text-muted-foreground space-y-1">
                <p>• 规格名称：子商品的规格描述，如"红色"、"64GB"、"大号"等</p>
                <p>• 子商品名称将自动生成："{parentGoodsName} - [规格名称]"</p>
                <p>• 所有子商品将自动关联到父商品（spuId = {parentGoodsId}）</p>
                <p>• 批量创建使用事务处理，确保数据一致性</p>
              </div>
            </CardContent>
          </Card>
        </div>

        <DialogFooter>
          <Button
            type="button"
            variant="outline"
            onClick={handleCancel}
            disabled={isSubmitting}
          >
            <X className="mr-2 h-4 w-4" />
            取消
          </Button>
          <Button
            type="button"
            onClick={handleSubmit}
            disabled={isSubmitting || specs.length === 0 || isLoadingParentGoods}
          >
            <Check className="mr-2 h-4 w-4" />
            {isSubmitting ? '创建中...' : `创建 ${specs.length} 个子商品`}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};