import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardFooter } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Trash2, Loader2, Edit, Info } from 'lucide-react';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import ProductInfoForm from './ProductInfoForm';

export default function MaterialCard({ material, onDelete, onUpdateName }) {
  const [name, setName] = useState(material.name);
  const [isSaving, setIsSaving] = useState(false);
  const [showProductInfo, setShowProductInfo] = useState(false);
  const originalName = material.name;

  useEffect(() => {
    setName(material.name);
  }, [material.name]);

  const handleNameChange = (e) => {
    setName(e.target.value);
  };

  const handleSaveName = async () => {
    if (name.trim() === '' || name === originalName || isSaving) {
        if (name.trim() === '') setName(originalName);
        return;
    }

    setIsSaving(true);
    try {
        await onUpdateName(material.id, { name });
    } catch (error) {
        console.error("Failed to update material name", error);
        setName(originalName);
    } finally {
        setIsSaving(false);
    }
  };

  const handleProductInfoSave = async (productData) => {
    try {
      await onUpdateName(material.id, productData);
      setShowProductInfo(false);
    } catch (error) {
      console.error("Failed to update product info", error);
    }
  };

  return (
    <Card className="overflow-hidden group transition-all duration-300 hover:shadow-xl hover:-translate-y-1">
      <CardContent className="p-0">
        <div className="aspect-square bg-slate-100 flex items-center justify-center">
            {material.file_url ? (
                <img 
                    src={material.file_url} 
                    alt={material.name} 
                    className="w-full h-full object-cover" 
                />
            ) : (
                 <div className="text-slate-400">无图</div>
            )}
        </div>
      </CardContent>
      <CardFooter className="p-3 bg-white flex flex-col items-start gap-2">
        <div className="w-full relative">
          <Input
            value={name}
            onChange={handleNameChange}
            onBlur={handleSaveName}
            onKeyDown={(e) => { if (e.key === 'Enter') e.target.blur(); }}
            className="font-semibold text-sm text-slate-800 w-full h-8 pr-8"
            disabled={isSaving}
          />
          {isSaving && <Loader2 className="w-4 h-4 animate-spin absolute right-2 top-1/2 -translate-y-1/2 text-slate-400" />}
        </div>
        
        {/* 商品信息预览 */}
        {material.type === 'product' && (
          <div className="w-full space-y-1">
            {material.sku && (
              <p className="text-xs text-slate-600">SKU: {material.sku}</p>
            )}
            {material.product_category && (
              <Badge variant="outline" className="text-xs">{material.product_category}</Badge>
            )}
            {material.matched_tmall_keywords && material.matched_tmall_keywords.length > 0 && (
              <div className="flex flex-wrap gap-1">
                {material.matched_tmall_keywords.slice(0, 2).map((keyword, index) => (
                  <Badge key={index} variant="outline" className="text-xs text-orange-600 border-orange-200">
                    {keyword}
                  </Badge>
                ))}
                {material.matched_tmall_keywords.length > 2 && (
                  <Badge variant="outline" className="text-xs text-slate-500">
                    +{material.matched_tmall_keywords.length - 2}
                  </Badge>
                )}
              </div>
            )}
          </div>
        )}
        
        <div className="w-full flex justify-between items-center">
          <div className="flex items-center gap-1">
            {material.category && (
              <Badge variant="secondary">{material.category}</Badge>
            )}
            {material.type === 'product' && (
              <Dialog open={showProductInfo} onOpenChange={setShowProductInfo}>
                <DialogTrigger asChild>
                  <Button variant="ghost" size="icon" className="w-6 h-6">
                    <Info className="w-3 h-3 text-blue-500" />
                  </Button>
                </DialogTrigger>
                <DialogContent className="max-w-2xl">
                  <DialogHeader>
                    <DialogTitle>商品详细信息</DialogTitle>
                  </DialogHeader>
                  <ProductInfoForm 
                    material={material} 
                    onSave={handleProductInfoSave}
                    onCancel={() => setShowProductInfo(false)}
                  />
                </DialogContent>
              </Dialog>
            )}
          </div>
          
          <AlertDialog>
            <AlertDialogTrigger asChild>
              <Button variant="ghost" size="icon" className="w-7 h-7">
                  <Trash2 className="w-4 h-4 text-red-500" />
              </Button>
            </AlertDialogTrigger>
            <AlertDialogContent>
              <AlertDialogHeader>
                <AlertDialogTitle>确定要删除吗?</AlertDialogTitle>
                <AlertDialogDescription>
                  此操作无法撤销。这将永久删除素材 "{originalName}"。
                </AlertDialogDescription>
              </AlertDialogHeader>
              <AlertDialogFooter>
                <AlertDialogCancel>取消</AlertDialogCancel>
                <AlertDialogAction onClick={() => onDelete(material.id)} className="bg-red-600 hover:bg-red-700">
                  删除
                </AlertDialogAction>
              </AlertDialogFooter>
            </AlertDialogContent>
          </AlertDialog>
        </div>
      </CardFooter>
    </Card>
  );
}