import React, { useState } from 'react';
import { useMutation } from '@tanstack/react-query';
import { Plus, Trash2, Check, X } 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 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: 0,
            categoryId2: 0,
            categoryId3: 0,
            goodsType: 1,
            supplierId: null,
            merchantId: null,
            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();
  };

  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>
            </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}
          >
            <Check className="mr-2 h-4 w-4" />
            {isSubmitting ? '创建中...' : `创建 ${specs.length} 个子商品`}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};