import { useState } from "react";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Calendar } from "@/components/ui/calendar";
import { Button } from "@/components/ui/button";
import { CalendarIcon, Sparkles, Loader2 } from "lucide-react";
import { format } from "date-fns";
import { cn } from "@/lib/utils";
import { invokeEdge } from "@/lib/edgeClient";
import { useToast } from "@/hooks/use-toast";

interface Category {
  id: string;
  name: string;
  is_active: boolean;
}

interface Brand {
  id: string;
  name: string;
  is_active: boolean;
}

interface ProductBasicInfoProps {
  formData: {
    name: string;
    description: string;
    price: string;
    stock_quantity: string;
    category: string;
    brand: string;
    release_date: Date | null;
  };
  categories: Category[];
  brands: Brand[];
  onChange: (field: string, value: any) => void;
}

export function ProductBasicInfo({ formData, categories, brands, onChange }: ProductBasicInfoProps) {
  const { toast } = useToast();
  const [generatingDesc, setGeneratingDesc] = useState(false);

  const handleGenerateDescription = async () => {
    if (!formData.name.trim()) {
      toast({ title: "请先填写商品名称", variant: "destructive" });
      return;
    }
    setGeneratingDesc(true);
    try {
      const res = await invokeEdge<{ description?: string; error?: string }>(
        "product-description-generate",
        {
          body: {
            name: formData.name,
            brand: formData.brand || undefined,
            category: formData.category || undefined,
            current: formData.description || undefined,
          },
          timeoutMs: 45_000,
        },
      );
      if (res?.description) {
        onChange("description", res.description);
        toast({ title: "AI 描述已生成" });
      } else {
        toast({ title: res?.error || "生成失败", variant: "destructive" });
      }
    } catch (e: any) {
      const msg = e?.message || "生成失败";
      const friendly = msg.includes("429")
        ? "调用过于频繁，请稍后再试"
        : msg.includes("402")
          ? "AI 额度不足，请到工作区充值"
          : msg;
      toast({ title: friendly, variant: "destructive" });
    } finally {
      setGeneratingDesc(false);
    }
  };

  return (
    <div className="space-y-6">
      {/* 名称和价格 */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        <div className="space-y-2">
          <Label htmlFor="name" className="text-sm font-medium">
            商品名称 <span className="text-destructive">*</span>
          </Label>
          <Input
            id="name"
            value={formData.name}
            onChange={(e) => onChange("name", e.target.value)}
            placeholder="请输入商品名称"
            className="h-11 transition-all focus:ring-2 focus:ring-primary/20"
          />
        </div>

        <div className="space-y-2">
          <Label htmlFor="price" className="text-sm font-medium">
            价格 <span className="text-destructive">*</span>
          </Label>
          <div className="relative">
            <span className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground">¥</span>
            <Input
              id="price"
              type="number"
              step="0.01"
              value={formData.price}
              onChange={(e) => onChange("price", e.target.value)}
              placeholder="0.00"
              className="h-11 pl-8 transition-all focus:ring-2 focus:ring-primary/20"
            />
          </div>
        </div>
      </div>

      {/* 分类和品牌 */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        <div className="space-y-2">
          <Label className="text-sm font-medium">分类</Label>
          <Select
            value={formData.category}
            onValueChange={(value) => onChange("category", value)}
          >
            <SelectTrigger className="h-11">
              <SelectValue placeholder="选择分类" />
            </SelectTrigger>
            <SelectContent>
              {categories.map((cat) => (
                <SelectItem key={cat.id} value={cat.name}>
                  {cat.name}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>

        <div className="space-y-2">
          <Label className="text-sm font-medium">品牌</Label>
          <Select
            value={formData.brand}
            onValueChange={(value) => onChange("brand", value)}
          >
            <SelectTrigger className="h-11">
              <SelectValue placeholder="选择品牌" />
            </SelectTrigger>
            <SelectContent>
              {brands.map((brand) => (
                <SelectItem key={brand.id} value={brand.name}>
                  {brand.name}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
      </div>

      {/* 库存和发布时间 */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        <div className="space-y-2">
          <Label htmlFor="stock" className="text-sm font-medium">
            库存数量 <span className="text-destructive">*</span>
          </Label>
          <Input
            id="stock"
            type="number"
            value={formData.stock_quantity}
            onChange={(e) => onChange("stock_quantity", e.target.value)}
            placeholder="请输入库存数量"
            className="h-11 transition-all focus:ring-2 focus:ring-primary/20"
          />
        </div>

        <div className="space-y-2">
          <Label className="text-sm font-medium">发布时间</Label>
          <Popover>
            <PopoverTrigger asChild>
              <Button
                variant="outline"
                className={cn(
                  "w-full h-11 justify-start text-left font-normal",
                  !formData.release_date && "text-muted-foreground"
                )}
              >
                <CalendarIcon className="mr-2 h-4 w-4" />
                {formData.release_date ? (
                  format(formData.release_date, "yyyy-MM-dd")
                ) : (
                  <span>选择发布时间</span>
                )}
              </Button>
            </PopoverTrigger>
            <PopoverContent className="w-auto p-0" align="start">
              <Calendar
                mode="single"
                selected={formData.release_date || undefined}
                onSelect={(date) => onChange("release_date", date || null)}
                initialFocus
                className="p-3 pointer-events-auto"
              />
            </PopoverContent>
          </Popover>
        </div>
      </div>

      {/* 描述 */}
      <div className="space-y-2">
        <div className="flex items-center justify-between">
          <Label htmlFor="description" className="text-sm font-medium">商品描述</Label>
          <Button
            type="button"
            size="sm"
            variant="outline"
            onClick={handleGenerateDescription}
            disabled={generatingDesc || !formData.name.trim()}
            className="h-8 gap-1.5"
          >
            {generatingDesc ? (
              <>
                <Loader2 className="h-3.5 w-3.5 animate-spin" />
                生成中...
              </>
            ) : (
              <>
                <Sparkles className="h-3.5 w-3.5" />
                AI 生成描述
              </>
            )}
          </Button>
        </div>
        <Textarea
          id="description"
          value={formData.description}
          onChange={(e) => onChange("description", e.target.value)}
          placeholder="请输入商品描述，或点击右上角「AI 生成描述」自动撰写..."
          rows={6}
          className="resize-none transition-all focus:ring-2 focus:ring-primary/20"
        />
      </div>
    </div>
  );
}
