import { useRef, useState } from "react";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Upload, X, Video, Play, Link, Trash2, Sparkles, Image as ImageIcon, AlertCircle, RefreshCw } from "lucide-react";
import { useToast } from "@/hooks/use-toast";
import { supabase } from "@/integrations/supabase/client";
import { cn } from "@/lib/utils";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";

interface ProductVideoUploadProps {
  videoUrl: string | null;
  onChange: (videoUrl: string | null) => void;
  /** 用于 AI 生成的上下文 */
  productName?: string;
  productDescription?: string;
  /** 已上传的商品图，作为图生视频的参考图 */
  referenceImageUrl?: string | null;
}

type AIMode = "text" | "image";
type Aspect = "16:9" | "9:16" | "1:1";

export function ProductVideoUpload({
  videoUrl,
  onChange,
  productName,
  productDescription,
  referenceImageUrl,
}: ProductVideoUploadProps) {
  const { toast } = useToast();
  const [uploading, setUploading] = useState(false);
  const [generating, setGenerating] = useState(false);
  const [urlInput, setUrlInput] = useState("");
  const [aiMode, setAiMode] = useState<AIMode>(referenceImageUrl ? "image" : "text");
  const [duration, setDuration] = useState<5 | 10>(5);
  const [aspect, setAspect] = useState<Aspect>("16:9");
  const [extraPrompt, setExtraPrompt] = useState("");
  const [lastError, setLastError] = useState<string | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleVideoUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    if (!file.type.startsWith("video/")) {
      toast({ title: "错误", description: "请上传视频格式文件", variant: "destructive" });
      return;
    }
    if (file.size > 100 * 1024 * 1024) {
      toast({ title: "错误", description: "视频大小不能超过 100MB", variant: "destructive" });
      return;
    }

    setUploading(true);
    try {
      const fileExt = file.name.split(".").pop();
      const fileName = `product_video_${Date.now()}.${fileExt}`;
      const filePath = `videos/${fileName}`;
      const { error: uploadError } = await supabase.storage
        .from("product-images")
        .upload(filePath, file);
      if (uploadError) throw uploadError;
      const { data } = supabase.storage.from("product-images").getPublicUrl(filePath);
      onChange(data.publicUrl);
      toast({ title: "成功", description: "视频上传成功" });
    } catch (error) {
      console.error("Error uploading video:", error);
      toast({ title: "错误", description: "视频上传失败，请重试", variant: "destructive" });
    } finally {
      setUploading(false);
      if (fileInputRef.current) fileInputRef.current.value = "";
    }
  };

  const handleUrlSubmit = () => {
    const trimmedUrl = urlInput.trim();
    if (!trimmedUrl) {
      toast({ title: "错误", description: "请输入视频链接", variant: "destructive" });
      return;
    }
    try {
      new URL(trimmedUrl);
    } catch {
      toast({ title: "错误", description: "请输入有效的视频链接", variant: "destructive" });
      return;
    }
    onChange(trimmedUrl);
    setUrlInput("");
    toast({ title: "成功", description: "视频链接已添加" });
  };

  const handleAIGenerate = async () => {
    if (!productName?.trim()) {
      toast({
        title: "缺少商品信息",
        description: "请先填写商品名称后再生成视频",
        variant: "destructive",
      });
      return;
    }
    if (aiMode === "image" && !referenceImageUrl) {
      toast({
        title: "缺少参考图",
        description: "图生视频需要先上传一张商品主图",
        variant: "destructive",
      });
      return;
    }

    setGenerating(true);
    setLastError(null);
    try {
      const { data, error } = await supabase.functions.invoke("product-video-generate", {
        body: {
          name: productName,
          description: productDescription,
          extraPrompt: extraPrompt.trim() || undefined,
          referenceImage: aiMode === "image" ? referenceImageUrl : undefined,
          duration,
          aspectRatio: aspect,
        },
      });
      if (error) throw error;
      if (!data?.url) throw new Error("未返回视频地址");
      onChange(data.url);
      setLastError(null);
      toast({
        title: "生成成功",
        description: `已生成 ${duration} 秒商品视频`,
      });
    } catch (e: any) {
      console.error("AI 视频生成失败", e);
      const raw = e?.message || e?.context?.error || "生成失败，请稍后重试";
      const msg = typeof raw === "string" ? raw : "生成失败，请稍后重试";
      setLastError(msg);
      toast({
        title: "AI 视频生成失败",
        description: msg,
        variant: "destructive",
      });
    } finally {
      setGenerating(false);
    }
  };

  const removeVideo = () => {
    onChange(null);
    setUrlInput("");
  };

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <Label className="text-sm font-medium">商品视频</Label>
        <span className="text-xs text-muted-foreground">{videoUrl ? "已添加" : "未添加"}</span>
      </div>

      {videoUrl ? (
        <div className="relative aspect-video rounded-xl overflow-hidden border-2 border-border bg-black">
          <video src={videoUrl} controls className="w-full h-full object-contain" />
          <Button
            variant="destructive"
            size="icon"
            className="absolute top-2 right-2 h-8 w-8 shadow-md"
            onClick={removeVideo}
          >
            <X className="h-4 w-4" />
          </Button>
          <div className="absolute top-2 left-2 bg-primary text-primary-foreground text-xs px-2 py-1 rounded-md font-medium shadow-sm flex items-center gap-1">
            <Play className="h-3 w-3" />
            视频
          </div>
        </div>
      ) : (
        <Tabs defaultValue="ai" className="w-full">
          <TabsList className="grid w-full grid-cols-3">
            <TabsTrigger value="ai" className="flex items-center gap-1">
              <Sparkles className="h-4 w-4" />
              AI 生成
            </TabsTrigger>
            <TabsTrigger value="upload" className="flex items-center gap-1">
              <Upload className="h-4 w-4" />
              本地上传
            </TabsTrigger>
            <TabsTrigger value="url" className="flex items-center gap-1">
              <Link className="h-4 w-4" />
              在线链接
            </TabsTrigger>
          </TabsList>

          {/* AI 生成 */}
          <TabsContent value="ai" className="mt-4 space-y-3">
            <div className="rounded-xl border-2 border-dashed border-muted-foreground/25 p-4 space-y-3">
              <div className="grid grid-cols-2 gap-2">
                <Button
                  type="button"
                  variant={aiMode === "text" ? "default" : "outline"}
                  size="sm"
                  onClick={() => setAiMode("text")}
                  className="justify-center"
                >
                  <Sparkles className="h-3.5 w-3.5 mr-1.5" />
                  文生视频
                </Button>
                <Button
                  type="button"
                  variant={aiMode === "image" ? "default" : "outline"}
                  size="sm"
                  onClick={() => setAiMode("image")}
                  disabled={!referenceImageUrl}
                  className="justify-center"
                >
                  <ImageIcon className="h-3.5 w-3.5 mr-1.5" />
                  图生视频{!referenceImageUrl && "（需主图）"}
                </Button>
              </div>

              <div className="grid grid-cols-2 gap-2">
                <div className="space-y-1">
                  <Label className="text-xs text-muted-foreground">时长</Label>
                  <Select
                    value={String(duration)}
                    onValueChange={(v) => setDuration(Number(v) as 5 | 10)}
                  >
                    <SelectTrigger className="h-9">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="5">5 秒</SelectItem>
                      <SelectItem value="10">10 秒</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div className="space-y-1">
                  <Label className="text-xs text-muted-foreground">比例</Label>
                  <Select value={aspect} onValueChange={(v) => setAspect(v as Aspect)} disabled={aiMode === "image"}>
                    <SelectTrigger className="h-9">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="16:9">16:9 横屏</SelectItem>
                      <SelectItem value="9:16">9:16 竖屏</SelectItem>
                      <SelectItem value="1:1">1:1 方形</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>

              <div className="space-y-1">
                <Label className="text-xs text-muted-foreground">补充提示词（可选）</Label>
                <Textarea
                  value={extraPrompt}
                  onChange={(e) => setExtraPrompt(e.target.value)}
                  placeholder="例如：缓慢环绕镜头展示，暖色调灯光，桌面场景"
                  rows={2}
                  className="text-sm resize-none"
                />
              </div>

              <Button
                type="button"
                onClick={handleAIGenerate}
                disabled={generating}
                className="w-full"
              >
                {generating ? (
                  <>
                    <div className="h-4 w-4 mr-2 border-2 border-current border-t-transparent rounded-full animate-spin" />
                    生成中（约 1-3 分钟）...
                  </>
                ) : (
                  <>
                    <Sparkles className="h-4 w-4 mr-2" />
                    开始生成
                  </>
                )}
              </Button>
              {lastError && !generating && (
                <div className="rounded-lg border border-destructive/40 bg-destructive/10 p-3 space-y-2">
                  <div className="flex items-start gap-2 text-xs text-destructive">
                    <AlertCircle className="h-4 w-4 shrink-0 mt-0.5" />
                    <div className="flex-1 break-words">
                      <div className="font-medium mb-0.5">上次生成失败</div>
                      <div className="opacity-90">{lastError}</div>
                    </div>
                  </div>
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={handleAIGenerate}
                    className="w-full border-destructive/40 text-destructive hover:bg-destructive/10 hover:text-destructive"
                  >
                    <RefreshCw className="h-3.5 w-3.5 mr-1.5" />
                    一键重试
                  </Button>
                </div>
              )}
              <p className="text-xs text-muted-foreground">
                由通义万相生成；模型与服务商可在 AI 配置中心切换（purpose=product_video）。turbo 模型固定 5 秒，如需 10 秒请切换至 plus 模型。
              </p>
            </div>
          </TabsContent>

          {/* 本地上传 */}
          <TabsContent value="upload" className="mt-4">
            <label
              className={cn(
                "aspect-video rounded-xl border-2 border-dashed flex flex-col items-center justify-center cursor-pointer transition-all duration-200",
                "border-muted-foreground/25 hover:border-primary hover:bg-primary/5",
                uploading && "pointer-events-none opacity-50",
              )}
            >
              <input
                ref={fileInputRef}
                type="file"
                accept="video/*"
                className="hidden"
                onChange={handleVideoUpload}
                disabled={uploading}
              />
              {uploading ? (
                <div className="flex flex-col items-center gap-2">
                  <div className="h-10 w-10 border-2 border-primary border-t-transparent rounded-full animate-spin" />
                  <span className="text-sm text-muted-foreground">上传中...</span>
                </div>
              ) : (
                <div className="flex flex-col items-center gap-3">
                  <div className="h-14 w-14 rounded-full bg-muted flex items-center justify-center">
                    <Upload className="h-6 w-6 text-muted-foreground" />
                  </div>
                  <span className="text-sm text-muted-foreground font-medium">点击上传商品视频</span>
                  <span className="text-xs text-muted-foreground">支持 MP4、WebM 格式，最大 100MB</span>
                </div>
              )}
            </label>
          </TabsContent>

          {/* 在线链接 */}
          <TabsContent value="url" className="mt-4 space-y-3">
            <div className="flex gap-2">
              <Input
                placeholder="粘贴视频链接，如阿里云、腾讯云视频URL"
                value={urlInput}
                onChange={(e) => setUrlInput(e.target.value)}
                onKeyDown={(e) => e.key === "Enter" && handleUrlSubmit()}
              />
              <Button onClick={handleUrlSubmit} className="shrink-0">
                添加
              </Button>
            </div>
            <p className="text-xs text-muted-foreground">支持 MP4、WebM 等视频格式的在线链接</p>
          </TabsContent>
        </Tabs>
      )}

      <p className="text-xs text-muted-foreground flex items-center gap-1">
        <Video className="h-3 w-3" />
        视频将在商品详情轮播图中展示，建议上传商品展示或使用教程视频
      </p>
    </div>
  );
}
