import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { format } from "date-fns";
import { supabase } from "@/integrations/supabase/client";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { useToast } from "@/hooks/use-toast";
import { Save, ArrowLeft, Package, ImageIcon, Settings2, ToggleLeft, Video, Mail, Send } from "lucide-react";
import { SpecificationCopyDialog } from "@/components/admin/SpecificationCopyDialog";
import { ProductBasicInfo } from "@/components/admin/product-edit/ProductBasicInfo";
import { ProductImageUpload } from "@/components/admin/product-edit/ProductImageUpload";
import { ProductVideoUpload } from "@/components/admin/product-edit/ProductVideoUpload";
import { ProductSpecifications } from "@/components/admin/product-edit/ProductSpecifications";
import { ProductStatusToggle } from "@/components/admin/product-edit/ProductStatusToggle";
import { Input } from "@/components/ui/input";
import {
  Breadcrumb,
  BreadcrumbItem,
  BreadcrumbLink,
  BreadcrumbList,
  BreadcrumbPage,
  BreadcrumbSeparator,
} from "@/components/ui/breadcrumb";

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

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

interface ProductEditPageProps {
  embedded?: boolean;
  productId?: string | null;
}

export default function ProductEditPage({ embedded = false, productId: propProductId }: ProductEditPageProps = {}) {
  const navigate = useNavigate();
  const id = propProductId;
  const { toast } = useToast();
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [categories, setCategories] = useState<Category[]>([]);
  const [brands, setBrands] = useState<Brand[]>([]);
  const [specsCopyDialogOpen, setSpecsCopyDialogOpen] = useState(false);
  const [email, setEmail] = useState("");
  const [sendingEmail, setSendingEmail] = useState(false);

  const [formData, setFormData] = useState({
    name: "",
    description: "",
    price: "",
    stock_quantity: "",
    category: "",
    brand: "",
    images: [] as string[],
    video_url: null as string | null,
    is_active: true,
    is_recommended: false,
    is_hot: false,
    specifications: [] as Array<{ key: string; value: string }>,
    release_date: null as Date | null,
  });

  useEffect(() => {
    fetchCategories();
    fetchBrands();
    if (id && id !== "new") {
      fetchProduct();
    } else {
      setLoading(false);
    }
  }, [id]);

  const fetchCategories = async () => {
    try {
      const { data, error } = await supabase
        .from("categories")
        .select("id, name, is_active")
        .eq("is_active", true)
        .order("display_order", { ascending: true });
      if (error) throw error;
      setCategories(data || []);
    } catch (error) {
      console.error("Error fetching categories:", error);
    }
  };

  const fetchBrands = async () => {
    try {
      const { data, error } = await supabase
        .from("brands")
        .select("id, name, is_active")
        .eq("is_active", true)
        .order("display_order", { ascending: true });
      if (error) throw error;
      setBrands(data || []);
    } catch (error) {
      console.error("Error fetching brands:", error);
    }
  };

  const fetchProduct = async () => {
    try {
      const { data, error } = await supabase
        .from("products")
        .select("*")
        .eq("id", id)
        .single();

      if (error) throw error;

      if (data) {
        const existingImages = data.images || (data.image_url ? [data.image_url] : []);
        const specificationsArray = data.specifications
          ? Object.entries(data.specifications).map(([key, value]) => ({ key, value: value as string }))
          : [];

        setFormData({
          name: data.name,
          description: data.description || "",
          price: data.price.toString(),
          stock_quantity: data.stock_quantity.toString(),
          category: data.category || "",
          brand: data.brand || "",
          images: existingImages,
          video_url: (data as any).video_url || null,
          is_active: data.is_active,
          is_recommended: data.is_recommended,
          is_hot: data.is_hot,
          specifications: specificationsArray,
          release_date: data.release_date ? new Date(data.release_date) : null,
        });
      }
    } catch (error) {
      console.error("Error fetching product:", error);
      toast({
        title: "错误",
        description: "获取商品信息失败",
        variant: "destructive",
      });
    } finally {
      setLoading(false);
    }
  };

  const handleFieldChange = (field: string, value: any) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
  };

  const handleCopySpecs = (copiedSpecs: Array<{ key: string; value: string }>) => {
    setFormData((prev) => ({
      ...prev,
      specifications: [...prev.specifications, ...copiedSpecs],
    }));
  };

  const handleSubmit = async () => {
    if (!formData.name || !formData.price || !formData.stock_quantity) {
      toast({
        title: "错误",
        description: "请填写必填字段（商品名称、价格、库存数量）",
        variant: "destructive",
      });
      return;
    }

    setSaving(true);

    try {
      const specificationsObj = formData.specifications.reduce((acc, spec) => {
        const key = (spec.key || "").toString().trim();
        const val = (spec.value != null ? String(spec.value) : "").trim();
        if (key && val) {
          acc[key] = val;
        }
        return acc;
      }, {} as Record<string, string>);

      const productData = {
        name: formData.name,
        description: formData.description,
        price: parseFloat(formData.price),
        stock_quantity: parseInt(formData.stock_quantity),
        category: formData.category || null,
        brand: formData.brand || null,
        image_url: formData.images.length > 0 ? formData.images[0] : null,
        images: formData.images.length > 0 ? formData.images : null,
        video_url: formData.video_url,
        is_active: formData.is_active,
        is_recommended: formData.is_recommended,
        is_hot: formData.is_hot,
        specifications: Object.keys(specificationsObj).length > 0 ? specificationsObj : null,
        release_date: formData.release_date ? format(formData.release_date, "yyyy-MM-dd") : null,
      };

      // 通过 Edge Function 保存，绕过 RLS
      const { data: result, error } = await supabase.functions.invoke("product-operations", {
        body: {
          operation: id && id !== "new" ? "product.update" : "product.create",
          params: id && id !== "new" ? { id, ...productData } : productData,
        },
      });

      if (error || !result?.success) {
        throw new Error(result?.error || error?.message || "保存失败");
      }

      toast({ title: "成功", description: result?.message || "保存成功" });
      navigate("/admin?tab=products");
    } catch (error) {
      console.error("Error saving product:", error);
      toast({
        title: "错误",
        description: error instanceof Error ? error.message : "保存商品失败",
        variant: "destructive",
      });
    } finally {
      setSaving(false);
    }
  };

  const handleSendEmail = async () => {
    if (!email) {
      toast({ title: "错误", description: "请输入邮箱地址", variant: "destructive" });
      return;
    }
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
      toast({ title: "错误", description: "请输入有效的邮箱地址", variant: "destructive" });
      return;
    }

    setSendingEmail(true);
    try {
      // 1. 先保存商品到数据库
      const specificationsObj = formData.specifications.reduce((acc, spec) => {
        const key = (spec.key || "").toString().trim();
        const val = (spec.value != null ? String(spec.value) : "").trim();
        if (key && val) acc[key] = val;
        return acc;
      }, {} as Record<string, string>);

      const productData = {
        name: formData.name,
        description: formData.description,
        price: parseFloat(formData.price),
        stock_quantity: parseInt(formData.stock_quantity),
        category: formData.category || null,
        brand: formData.brand || null,
        image_url: formData.images.length > 0 ? formData.images[0] : null,
        images: formData.images.length > 0 ? formData.images : null,
        video_url: formData.video_url,
        is_active: formData.is_active,
        is_recommended: formData.is_recommended,
        is_hot: formData.is_hot,
        specifications: Object.keys(specificationsObj).length > 0 ? specificationsObj : null,
        release_date: formData.release_date ? format(formData.release_date, "yyyy-MM-dd") : null,
      };

      const { data: saveResult, error: saveError } = await supabase.functions.invoke("product-operations", {
        body: {
          operation: id && id !== "new" ? "product.update" : "product.create",
          params: id && id !== "new" ? { id, ...productData } : productData,
        },
      });

      if (saveError || !saveResult?.success) {
        throw new Error(saveResult?.error || saveError?.message || "保存商品失败");
      }

      // 2. 构建邮件内容
      const emailSubject = `商品推荐：${formData.name}`;
      const emailBody = [
        `您好！`,
        ``,
        `为您推荐以下商品：`,
        ``,
        `商品名称：${formData.name}`,
        `商品价格：¥${formData.price}`,
        formData.brand ? `品牌：${formData.brand}` : "",
        formData.category ? `分类：${formData.category}` : "",
        formData.description ? `描述：${formData.description}` : "",
        formData.images.length > 0 ? `图片：${formData.images[0]}` : "",
        formData.video_url ? `视频：${formData.video_url}` : "",
        ``,
        `如需更多信息或下单，欢迎随时联系我们。`,
        ``,
        `钱江云 B2B 平台`,
      ].filter(Boolean).join("\n");

      const emailHtml = [
        `<h2>${formData.name}</h2>`,
        formData.images.length > 0 ? `<img src="${formData.images[0]}" style="max-width:600px" alt="${formData.name}" />` : "",
        formData.video_url
          ? `<div style="margin:16px 0;position:relative;max-width:600px">
               <a href="${formData.video_url}" target="_blank" style="display:block;position:relative">
                 <img src="${formData.images[0]}" style="width:100%;max-width:600px;border-radius:8px" alt="${formData.name}" />
                 <div style="position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);width:64px;height:64px;background:rgba(0,0,0,0.6);border-radius:50%;display:flex;align-items:center;justify-content:center">
                   <div style="width:0;height:0;border-left:20px solid white;border-top:12px solid transparent;border-bottom:12px solid transparent;margin-left:4px"></div>
                 </div>
               </a>
               <p style="margin-top:4px;font-size:12px;color:#666">点击图片播放视频</p>
             </div>`
          : "",
        `<p><strong>价格：</strong>¥${formData.price}</p>`,
        formData.brand ? `<p><strong>品牌：</strong>${formData.brand}</p>` : "",
        formData.category ? `<p><strong>分类：</strong>${formData.category}</p>` : "",
        formData.description ? `<p>${formData.description.replace(/\n/g, "<br/>")}</p>` : "",
        `<hr/>`,
        `<p style="color:#666;font-size:12px">钱江云 B2B 平台</p>`,
      ].filter(Boolean).join("\n");

      // 3. 获取当前用户
      const { data: { user } } = await supabase.auth.getUser();

      // 4. 创建草稿邮件
      const { data: draft, error: draftError } = await supabase
        .from("emails")
        .insert([{
          user_id: user?.id,
          from_email: "system@store.com",
          to_email: email,
          subject: emailSubject,
          body_text: emailBody,
          body_html: emailHtml,
          status: "draft",
          metadata: {
            category: "product_inquiry",
            source: "product_share",
            product_name: formData.name,
            product_price: formData.price,
          },
        }])
        .select("id")
        .single();

      if (draftError) throw draftError;

      // 5. 调用 email-send-business 发送邮件
      const supabaseUrl = import.meta.env.VITE_SUPABASE_URL;
      const sendResponse = await fetch(`${supabaseUrl}/functions/v1/email-send-business`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email_id: draft.id }),
      });
      const sendResult = await sendResponse.json();
      if (!sendResult.success) throw new Error(sendResult.error || "邮件发送失败");

      toast({ title: "成功", description: "商品已保存，邮件已发送" });
      setEmail("");
    } catch (error) {
      console.error("Error sending email:", error);
      toast({
        title: "错误",
        description: error instanceof Error ? error.message : "操作失败",
        variant: "destructive",
      });
    } finally {
      setSendingEmail(false);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <div className="flex flex-col items-center gap-3">
          <div className="animate-spin rounded-full h-10 w-10 border-2 border-primary border-t-transparent"></div>
          <span className="text-sm text-muted-foreground">加载中...</span>
        </div>
      </div>
    );
  }

  return (
    <div className="max-w-5xl mx-auto space-y-6 pb-8">
      {/* 面包屑导航 */}
      <Breadcrumb>
        <BreadcrumbList>
          <BreadcrumbItem>
            <BreadcrumbLink onClick={() => navigate("/admin")} className="cursor-pointer">
              管理后台
            </BreadcrumbLink>
          </BreadcrumbItem>
          <BreadcrumbSeparator />
          <BreadcrumbItem>
            <BreadcrumbLink onClick={() => navigate("/admin?tab=products")} className="cursor-pointer">
              商品管理
            </BreadcrumbLink>
          </BreadcrumbItem>
          <BreadcrumbSeparator />
          <BreadcrumbItem>
            <BreadcrumbPage>{id === "new" ? "添加商品" : "编辑商品"}</BreadcrumbPage>
          </BreadcrumbItem>
        </BreadcrumbList>
      </Breadcrumb>

      {/* 页面标题和操作按钮 */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-semibold tracking-tight">
            {id === "new" ? "添加商品" : "编辑商品"}
          </h1>
          <p className="text-sm text-muted-foreground mt-1">
            {id === "new" ? "填写商品信息以创建新商品" : "修改商品的详细信息"}
          </p>
        </div>
        <div className="flex gap-3">
          <Button variant="outline" onClick={() => navigate("/admin?tab=products")}>
            <ArrowLeft className="w-4 h-4 mr-2" />
            返回
          </Button>
          <Button onClick={handleSubmit} disabled={saving} className="min-w-[100px]">
            {saving ? (
              <>
                <div className="h-4 w-4 mr-2 border-2 border-current border-t-transparent rounded-full animate-spin" />
                保存中
              </>
            ) : (
              <>
                <Save className="w-4 h-4 mr-2" />
                保存
              </>
            )}
          </Button>
        </div>
      </div>

      {/* 表单卡片 */}
      <div className="grid gap-6">
        {/* 基本信息 */}
        <Card>
          <CardHeader className="pb-4">
            <div className="flex items-center gap-3">
              <div className="h-10 w-10 rounded-lg bg-primary/10 flex items-center justify-center">
                <Package className="h-5 w-5 text-primary" />
              </div>
              <div>
                <CardTitle className="text-lg">基本信息</CardTitle>
                <CardDescription>商品的名称、价格和分类等基本属性</CardDescription>
              </div>
            </div>
          </CardHeader>
          <CardContent>
            <ProductBasicInfo
              formData={formData}
              categories={categories}
              brands={brands}
              onChange={handleFieldChange}
            />
          </CardContent>
        </Card>

        {/* 商品图片 */}
        <Card>
          <CardHeader className="pb-4">
            <div className="flex items-center gap-3">
              <div className="h-10 w-10 rounded-lg bg-primary/10 flex items-center justify-center">
                <ImageIcon className="h-5 w-5 text-primary" />
              </div>
              <div>
                <CardTitle className="text-lg">商品图片</CardTitle>
                <CardDescription>上传商品展示图片，第一张将作为封面</CardDescription>
              </div>
            </div>
          </CardHeader>
          <CardContent>
            <ProductImageUpload
              images={formData.images}
              onChange={(images) => handleFieldChange("images", images)}
              productName={formData.name}
              productDescription={formData.description}
            />
          </CardContent>
        </Card>

        {/* 商品视频 */}
        <Card>
          <CardHeader className="pb-4">
            <div className="flex items-center gap-3">
              <div className="h-10 w-10 rounded-lg bg-primary/10 flex items-center justify-center">
                <Video className="h-5 w-5 text-primary" />
              </div>
              <div>
                <CardTitle className="text-lg">商品视频</CardTitle>
                <CardDescription>上传商品展示视频，将在轮播图中优先展示</CardDescription>
              </div>
            </div>
          </CardHeader>
          <CardContent>
            <ProductVideoUpload
              videoUrl={formData.video_url}
              onChange={(url) => handleFieldChange("video_url", url)}
              productName={formData.name}
              productDescription={formData.description}
              referenceImageUrl={formData.images?.[0] || null}
            />
          </CardContent>
        </Card>

        {/* 商品规格 */}
        <Card>
          <CardHeader className="pb-4">
            <div className="flex items-center gap-3">
              <div className="h-10 w-10 rounded-lg bg-primary/10 flex items-center justify-center">
                <Settings2 className="h-5 w-5 text-primary" />
              </div>
              <div>
                <CardTitle className="text-lg">商品规格</CardTitle>
                <CardDescription>添加商品的详细规格参数信息</CardDescription>
              </div>
            </div>
          </CardHeader>
          <CardContent>
            <ProductSpecifications
              specifications={formData.specifications}
              onChange={(specs) => handleFieldChange("specifications", specs)}
              onOpenCopyDialog={() => setSpecsCopyDialogOpen(true)}
            />
          </CardContent>
        </Card>

        {/* 商品状态 */}
        <Card>
          <CardHeader className="pb-4">
            <div className="flex items-center gap-3">
              <div className="h-10 w-10 rounded-lg bg-primary/10 flex items-center justify-center">
                <ToggleLeft className="h-5 w-5 text-primary" />
              </div>
              <div>
                <CardTitle className="text-lg">商品状态</CardTitle>
                <CardDescription>控制商品的显示和推荐状态</CardDescription>
              </div>
            </div>
          </CardHeader>
          <CardContent>
            <ProductStatusToggle
              isActive={formData.is_active}
              isRecommended={formData.is_recommended}
              isHot={formData.is_hot}
              onChange={handleFieldChange}
            />
          </CardContent>
        </Card>

        {/* 发送邮件 */}
        <Card>
          <CardHeader className="pb-4">
            <div className="flex items-center gap-3">
              <div className="h-10 w-10 rounded-lg bg-primary/10 flex items-center justify-center">
                <Mail className="h-5 w-5 text-primary" />
              </div>
              <div>
                <CardTitle className="text-lg">发送商品邮件</CardTitle>
                <CardDescription>将商品信息发送到指定邮箱</CardDescription>
              </div>
            </div>
          </CardHeader>
          <CardContent>
            <div className="flex gap-3">
              <Input
                type="email"
                placeholder="请输入邮箱地址"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                className="flex-1"
              />
              <Button onClick={handleSendEmail} disabled={sendingEmail} className="min-w-[100px]">
                {sendingEmail ? (
                  <>
                    <div className="h-4 w-4 mr-2 border-2 border-current border-t-transparent rounded-full animate-spin" />
                    发送中
                  </>
                ) : (
                  <>
                    <Send className="w-4 h-4 mr-2" />
                    发送邮件
                  </>
                )}
              </Button>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* 规格复制对话框 */}
      <SpecificationCopyDialog
        open={specsCopyDialogOpen}
        onOpenChange={setSpecsCopyDialogOpen}
        onCopy={handleCopySpecs}
        currentProductId={id !== "new" ? id : null}
      />
    </div>
  );
}
