import React, { useState } from 'react';
import { Plus, Trash2, Copy, Save, X, Package } from 'lucide-react';
import { toast } from 'sonner';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';

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 { Input } from '@d8d/shared-ui-components/components/ui/input';
import { Label } from '@d8d/shared-ui-components/components/ui/label';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@d8d/shared-ui-components/components/ui/table';
import { Badge } from '@d8d/shared-ui-components/components/ui/badge';
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@d8d/shared-ui-components/components/ui/form';

interface BatchSpecCreatorInlineProps {
  // 初始规格模板
  initialSpecs?: Array<{
    name: string;
    price: number;
    costPrice: number;
    stock: number;
    sort: number;
  }>;

  // 回调函数
  onSpecsChange?: (specs: Array<{ name: string; price: number; costPrice: number; stock: number; sort: number }>) => void;
  onSaveTemplate?: (templateName: string, specs: Array<{ name: string; price: number; costPrice: number; stock: number; sort: number }>) => void;

  // 其他
  className?: string;
  disabled?: boolean;
}

// 添加规格表单的schema
const addSpecFormSchema = z.object({
  name: z.string().min(1, '规格名称不能为空').trim(),
  price: z.number().min(0, '价格不能为负数'),
  costPrice: z.number().min(0, '成本价不能为负数'),
  stock: z.number().int().min(0, '库存不能为负数'),
});

type AddSpecFormValues = {
  name: string;
  price: number;
  costPrice: number;
  stock: number;
};

export const BatchSpecCreatorInline: React.FC<BatchSpecCreatorInlineProps> = ({
  initialSpecs = [],
  onSpecsChange,
  onSaveTemplate,
  className = '',
  disabled = false
}) => {
  const [specs, setSpecs] = useState<Array<{
    id: number;
    name: string;
    price: number;
    costPrice: number;
    stock: number;
    sort: number;
  }>>(
    initialSpecs.map((spec, index) => ({
      id: Date.now() + index,
      ...spec
    }))
  );

  const [templateName, setTemplateName] = useState('');
  const [showSaveTemplate, setShowSaveTemplate] = useState(false);

  // 添加规格表单
  const form = useForm<AddSpecFormValues>({
    resolver: zodResolver(addSpecFormSchema),
    defaultValues: {
      name: '',
      price: 0,
      costPrice: 0,
      stock: 0,
    },
  });

  const onSubmit = (data: AddSpecFormValues) => {
    console.debug('表单提交数据:', data);
    // 检查规格名称是否重复（不区分大小写）
    const isDuplicate = specs.some(spec =>
      spec.name.toLowerCase() === data.name.trim().toLowerCase()
    );
    if (isDuplicate) {
      toast.error(`规格名称 "${data.name}" 已存在，请使用不同的名称`);
      return;
    }

    const newSpecWithId = {
      id: Date.now(),
      ...data,
      sort: specs.length
    };

    const updatedSpecs = [...specs, newSpecWithId];
    setSpecs(updatedSpecs);

    // 通知父组件
    if (onSpecsChange) {
      onSpecsChange(updatedSpecs.map(({ id, ...rest }) => rest));
    }

    // 重置表单
    form.reset({
      name: '',
      price: 0,
      costPrice: 0,
      stock: 0,
    });

    toast.success('规格已添加');
  };

  const onError = (errors: any) => {
    // 显示第一个错误消息
    console.debug('表单验证错误:', errors);
    if (errors && typeof errors === 'object') {
      const errorValues = Object.values(errors);
      for (const error of errorValues) {
        if (error && typeof error === 'object' && 'message' in error) {
          toast.error((error as any).message);
          return;
        }
      }
    }
    // 后备错误处理
    toast.error('表单验证失败');
  };


  const handleRemoveSpec = (id: number) => {
    const updatedSpecs = specs.filter(spec => spec.id !== id);
    setSpecs(updatedSpecs);

    // 通知父组件
    if (onSpecsChange) {
      onSpecsChange(updatedSpecs.map(({ id, ...rest }) => rest));
    }

    toast.success('规格已删除');
  };

  const handleDuplicateSpec = (index: number) => {
    const specToDuplicate = specs[index];
    const duplicatedSpec = {
      ...specToDuplicate,
      id: Date.now(),
      name: `${specToDuplicate.name} (副本)`,
      sort: specs.length
    };

    const updatedSpecs = [...specs, duplicatedSpec];
    setSpecs(updatedSpecs);

    // 通知父组件
    if (onSpecsChange) {
      onSpecsChange(updatedSpecs.map(({ id, ...rest }) => rest));
    }

    toast.success('规格已复制');
  };

  const handleUpdateSpec = (id: number, field: string, value: any) => {
    // 如果是更新名称字段，需要检查重复
    if (field === 'name') {
      const trimmedValue = value.trim();
      if (!trimmedValue) {
        toast.error('规格名称不能为空');
        return;
      }

      // 检查规格名称是否重复（不区分大小写），排除当前正在编辑的规格
      const isDuplicate = specs.some(spec =>
        spec.id !== id && spec.name.toLowerCase() === trimmedValue.toLowerCase()
      );
      if (isDuplicate) {
        toast.error(`规格名称 "${trimmedValue}" 已存在，请使用不同的名称`);
        return;
      }
    }

    const updatedSpecs = specs.map(spec => {
      if (spec.id === id) {
        return { ...spec, [field]: value };
      }
      return spec;
    });

    setSpecs(updatedSpecs);

    // 通知父组件
    if (onSpecsChange) {
      onSpecsChange(updatedSpecs.map(({ id, ...rest }) => rest));
    }
  };

  const handleSaveTemplate = () => {
    if (!templateName.trim()) {
      toast.error('请输入模板名称');
      return;
    }

    if (specs.length === 0) {
      toast.error('请先添加规格');
      return;
    }

    if (onSaveTemplate) {
      onSaveTemplate(templateName, specs.map(({ id, ...rest }) => rest));
      setTemplateName('');
      setShowSaveTemplate(false);
      toast.success('模板保存成功');
    }
  };

  const handleLoadTemplate = (templateSpecs: Array<{ name: string; price: number; costPrice: number; stock: number; sort: number }>) => {
    const newSpecs = templateSpecs.map((spec, index) => ({
      id: Date.now() + index,
      ...spec
    }));

    setSpecs(newSpecs);

    // 通知父组件
    if (onSpecsChange) {
      onSpecsChange(templateSpecs);
    }

    toast.success('模板已加载');
  };

  // 预定义模板
  const predefinedTemplates = [
    {
      name: '颜色规格模板',
      specs: [
        { name: '红色', price: 100, costPrice: 80, stock: 100, sort: 1 },
        { name: '蓝色', price: 100, costPrice: 80, stock: 100, sort: 2 },
        { name: '绿色', price: 100, costPrice: 80, stock: 100, sort: 3 },
        { name: '黑色', price: 100, costPrice: 80, stock: 100, sort: 4 },
        { name: '白色', price: 100, costPrice: 80, stock: 100, sort: 5 }
      ]
    },
    {
      name: '尺寸规格模板',
      specs: [
        { name: 'S码', price: 100, costPrice: 80, stock: 100, sort: 1 },
        { name: 'M码', price: 110, costPrice: 85, stock: 100, sort: 2 },
        { name: 'L码', price: 120, costPrice: 90, stock: 100, sort: 3 },
        { name: 'XL码', price: 130, costPrice: 95, stock: 100, sort: 4 }
      ]
    },
    {
      name: '容量规格模板',
      specs: [
        { name: '64GB', price: 2999, costPrice: 2500, stock: 50, sort: 1 },
        { name: '128GB', price: 3499, costPrice: 2800, stock: 50, sort: 2 },
        { name: '256GB', price: 3999, costPrice: 3200, stock: 50, sort: 3 },
        { name: '512GB', price: 4999, costPrice: 4000, stock: 30, sort: 4 }
      ]
    }
  ];

  const totalStock = specs.reduce((sum, spec) => sum + spec.stock, 0);
  const totalValue = specs.reduce((sum, spec) => sum + (spec.price * spec.stock), 0);
  const avgPrice = specs.length > 0 ? specs.reduce((sum, spec) => sum + spec.price, 0) / specs.length : 0;

  return (
    <Card className={className} data-testid="batch-spec-creator-inline">
      <CardHeader>
        <CardTitle data-testid="batch-spec-creator-title">批量创建规格</CardTitle>
        <CardDescription>
          添加多个商品规格，创建后将作为子商品批量生成
        </CardDescription>
      </CardHeader>
      <CardContent className="space-y-4">
        {/* 添加新规格表单 */}
        <Form {...form}>
          <form
            onSubmit={form.handleSubmit(onSubmit, onError)}
            className="grid grid-cols-1 md:grid-cols-6 gap-4 p-4 border rounded-lg"
            data-testid="add-spec-form"
            noValidate
          >
            <div className="md:col-span-2">
              <FormField
                control={form.control}
                name="name"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel data-testid="spec-name-label">规格名称 *</FormLabel>
                    <FormControl>
                      <Input
                        placeholder="例如：红色、64GB、S码"
                        data-testid="spec-name-input"
                        disabled={disabled}
                        {...field}
                        onChange={(e) => {
                          field.onChange(e.target.value);
                        }}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>
            <div>
              <FormField
                control={form.control}
                name="price"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel data-testid="spec-price-label">价格</FormLabel>
                    <FormControl>
                      <Input
                        type="number"
                        min="0"
                        step="0.01"
                        placeholder="0.00"
                        data-testid="spec-price-input"
                        disabled={disabled}
                        {...field}
                        onChange={(e) => {
                          field.onChange(parseFloat(e.target.value) || 0);
                        }}
                        value={field.value === 0 ? '' : field.value}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>
            <div>
              <FormField
                control={form.control}
                name="costPrice"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel data-testid="spec-cost-price-label">成本价</FormLabel>
                    <FormControl>
                      <Input
                        type="number"
                        min="0"
                        step="0.01"
                        placeholder="0.00"
                        data-testid="spec-cost-price-input"
                        disabled={disabled}
                        {...field}
                        onChange={(e) => {
                          field.onChange(parseFloat(e.target.value) || 0);
                        }}
                        value={field.value === 0 ? '' : field.value}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>
            <div>
              <FormField
                control={form.control}
                name="stock"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel data-testid="spec-stock-label">库存</FormLabel>
                    <FormControl>
                      <Input
                        type="number"
                        min="0"
                        step="1"
                        placeholder="0"
                        data-testid="spec-stock-input"
                        disabled={disabled}
                        {...field}
                        onChange={(e) => {
                          field.onChange(parseInt(e.target.value) || 0);
                        }}
                        value={field.value === 0 ? '' : field.value}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>
            <div className="flex items-end">
              <Button
                type="submit"
                disabled={disabled || !form.watch('name').trim()}
                className="w-full"
                data-testid="add-spec-button"
              >
                <Plus className="mr-2 h-4 w-4" />
                添加
              </Button>
            </div>
          </form>
        </Form>

        {/* 预定义模板 */}
        <div data-testid="predefined-templates-section">
          <Label className="mb-2 block" data-testid="quick-templates-label">快速模板</Label>
          <div className="flex flex-wrap gap-2">
            {predefinedTemplates.map((template, index) => (
              <Badge
                key={index}
                variant="outline"
                className="cursor-pointer hover:bg-accent"
                onClick={() => !disabled && handleLoadTemplate(template.specs)}
                data-testid={`template-${template.name.replace(/\s+/g, '-').toLowerCase()}`}
              >
                <Copy className="mr-1 h-3 w-3" />
                {template.name}
              </Badge>
            ))}
          </div>
        </div>

        {/* 规格列表 */}
        {specs.length > 0 ? (
          <>
            <div className="overflow-x-auto" data-testid="specs-table-container">
              <Table data-testid="specs-table">
                <TableHeader>
                  <TableRow>
                    <TableHead data-testid="spec-name-header">规格名称</TableHead>
                    <TableHead data-testid="spec-price-header">价格</TableHead>
                    <TableHead data-testid="spec-cost-price-header">成本价</TableHead>
                    <TableHead data-testid="spec-stock-header">库存</TableHead>
                    <TableHead data-testid="spec-sort-header">排序</TableHead>
                    <TableHead className="text-right" data-testid="spec-actions-header">操作</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {specs.map((spec, index) => (
                    <TableRow key={spec.id} data-testid={`spec-row-${index}`}>
                      <TableCell className="font-medium" data-testid={`spec-name-cell-${index}`}>
                        <Input
                          value={spec.name}
                          onChange={(e) => handleUpdateSpec(spec.id, 'name', e.target.value)}
                          disabled={disabled}
                          data-testid={`spec-name-input-${index}`}
                        />
                      </TableCell>
                      <TableCell data-testid={`spec-price-cell-${index}`}>
                        <Input
                          type="number"
                          min="0"
                          step="0.01"
                          value={spec.price}
                          onChange={(e) => handleUpdateSpec(spec.id, 'price', parseFloat(e.target.value) || 0)}
                          disabled={disabled}
                          data-testid={`spec-price-input-${index}`}
                        />
                      </TableCell>
                      <TableCell data-testid={`spec-cost-price-cell-${index}`}>
                        <Input
                          type="number"
                          min="0"
                          step="0.01"
                          value={spec.costPrice}
                          onChange={(e) => handleUpdateSpec(spec.id, 'costPrice', parseFloat(e.target.value) || 0)}
                          disabled={disabled}
                          data-testid={`spec-cost-price-input-${index}`}
                        />
                      </TableCell>
                      <TableCell data-testid={`spec-stock-cell-${index}`}>
                        <Input
                          type="number"
                          min="0"
                          step="1"
                          value={spec.stock}
                          onChange={(e) => handleUpdateSpec(spec.id, 'stock', parseInt(e.target.value) || 0)}
                          disabled={disabled}
                          data-testid={`spec-stock-input-${index}`}
                        />
                      </TableCell>
                      <TableCell data-testid={`spec-sort-cell-${index}`}>
                        <Input
                          type="number"
                          min="0"
                          step="1"
                          value={spec.sort}
                          onChange={(e) => handleUpdateSpec(spec.id, 'sort', parseInt(e.target.value) || 0)}
                          disabled={disabled}
                          data-testid={`spec-sort-input-${index}`}
                        />
                      </TableCell>
                      <TableCell className="text-right" data-testid={`spec-actions-cell-${index}`}>
                        <div className="flex justify-end gap-2">
                          <Button
                            variant="ghost"
                            size="icon"
                            onClick={() => handleDuplicateSpec(index)}
                            disabled={disabled}
                            title="复制"
                            data-testid={`duplicate-spec-button-${index}`}
                          >
                            <Copy className="h-4 w-4" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="icon"
                            onClick={() => handleRemoveSpec(spec.id)}
                            disabled={disabled}
                            title="删除"
                            className="text-destructive hover:text-destructive"
                            data-testid={`remove-spec-button-${index}`}
                          >
                            <Trash2 className="h-4 w-4" />
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>

            {/* 统计信息 */}
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4 p-4 border rounded-lg" data-testid="specs-stats">
              <div className="space-y-1" data-testid="specs-count-stat">
                <div className="text-sm text-muted-foreground">规格数量</div>
                <div className="text-lg font-semibold">{specs.length}</div>
              </div>
              <div className="space-y-1" data-testid="total-stock-stat">
                <div className="text-sm text-muted-foreground">总库存</div>
                <div className="text-lg font-semibold">{totalStock}</div>
              </div>
              <div className="space-y-1" data-testid="avg-price-stat">
                <div className="text-sm text-muted-foreground">平均价格</div>
                <div className="text-lg font-semibold">¥{avgPrice.toFixed(2)}</div>
              </div>
              <div className="space-y-1" data-testid="total-value-stat">
                <div className="text-sm text-muted-foreground">总货值</div>
                <div className="text-lg font-semibold">¥{totalValue.toFixed(2)}</div>
              </div>
            </div>

            {/* 保存模板 */}
            <div className="flex justify-between items-center" data-testid="save-template-section">
              <div className="text-sm text-muted-foreground" data-testid="specs-summary">
                共 {specs.length} 个规格，将在创建商品后批量生成子商品
              </div>
              <div className="flex gap-2">
                {!showSaveTemplate ? (
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => setShowSaveTemplate(true)}
                    disabled={disabled}
                    data-testid="show-save-template-button"
                  >
                    <Save className="mr-2 h-4 w-4" />
                    保存为模板
                  </Button>
                ) : (
                  <div className="flex gap-2" data-testid="save-template-form">
                    <Input
                      placeholder="输入模板名称"
                      value={templateName}
                      onChange={(e) => setTemplateName(e.target.value)}
                      className="w-40"
                      disabled={disabled}
                      data-testid="template-name-input"
                    />
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={handleSaveTemplate}
                      disabled={disabled || !templateName.trim()}
                      data-testid="save-template-button"
                    >
                      保存
                    </Button>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => setShowSaveTemplate(false)}
                      disabled={disabled}
                      data-testid="cancel-save-template-button"
                    >
                      <X className="h-4 w-4" />
                    </Button>
                  </div>
                )}
              </div>
            </div>
          </>
        ) : (
          <div className="text-center py-8 border rounded-lg" data-testid="no-specs-placeholder">
            <Package className="h-12 w-12 mx-auto mb-2 text-muted-foreground" />
            <p className="text-muted-foreground" data-testid="no-specs-text">暂无规格</p>
            <p className="text-sm text-muted-foreground mt-1" data-testid="no-specs-description">
              添加规格后，将在创建商品时批量生成子商品
            </p>
          </div>
        )}
      </CardContent>
    </Card>
  );
};