import { useState, useEffect, useCallback } from "react";
import { supabase } from "@/integrations/supabase/client";
import { emailService } from "@/services/emailService";
import { useToast } from "@/hooks/use-toast";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Mail,
  Send,
  Inbox,
  SendHorizonal,
  Pencil,
  RefreshCw,
  Trash2,
  Eye,
  FileEdit,
  Loader2,
  MailOpen,
  MailCheck,
  AlertCircle,
  ShoppingBag,
  FileText,
  Truck,
  ClipboardCheck,
  AlertTriangle,
  CreditCard,
  Heart,
  LayoutGrid,
  Download,
  Paperclip,
  Reply,
  MessageSquare,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { format } from "date-fns";
import { zhCN } from "date-fns/locale";

type ViewType = "inbox" | "sent" | "drafts" | "compose";

interface CategoryDef {
  id: string;
  label: string;
  icon: React.ReactNode;
  color: string;
}

const CATEGORIES: CategoryDef[] = [
  { id: "product_inquiry", label: "商品咨询", icon: <ShoppingBag className="h-3.5 w-3.5" />, color: "text-blue-500" },
  { id: "order_placed", label: "订单下达", icon: <FileText className="h-3.5 w-3.5" />, color: "text-emerald-500" },
  { id: "order_fulfillment", label: "订单履约", icon: <Truck className="h-3.5 w-3.5" />, color: "text-amber-500" },
  { id: "delivery_receipt", label: "收货回执", icon: <ClipboardCheck className="h-3.5 w-3.5" />, color: "text-teal-500" },
  { id: "abnormal_order", label: "异常订单", icon: <AlertTriangle className="h-3.5 w-3.5" />, color: "text-red-500" },
  { id: "payment_notification", label: "支付通知", icon: <CreditCard className="h-3.5 w-3.5" />, color: "text-purple-500" },
  { id: "daily_greetings", label: "日常祝福", icon: <Heart className="h-3.5 w-3.5" />, color: "text-pink-500" },
];

const getCategoryById = (id: string | null) => CATEGORIES.find((c) => c.id === id);

/** emails 表实际字段类型 */
interface EmailRecord {
  id: string;
  user_id: string;
  from_email: string;
  to_email: string;
  cc_emails: string[];
  bcc_emails: string[];
  subject: string;
  body_html: string | null;
  body_text: string | null;
  status: string; // draft | sending | sent | delivered | read | failed
  sent_at: string | null;
  delivered_at: string | null;
  read_at: string | null;
  failed_at: string | null;
  failure_reason: string | null;
  message_id: string | null;
  thread_id: string | null;
  reply_to_message_id: string | null;
  attachments: Array<{ filename: string; content_type: string; size: number }>;
  metadata: Record<string, any> | null;
  created_at: string;
  updated_at: string;
  imap_uid: number | null;
  in_reply_to: string | null;
  cc: string | null;
  has_attachments: boolean | null;
}

/** 从 metadata 中提取 category */
const getEmailCategory = (email: EmailRecord): string | null => {
  return email.metadata?.category || null;
};

/** 获取邮件正文（优先 body_text） */
const getEmailBody = (email: EmailRecord): string => {
  return email.body_text || email.body_html || "";
};

/** 获取邮件显示时间 */
const getEmailTime = (email: EmailRecord): string => {
  return email.sent_at || email.delivered_at || email.created_at;
};

/** 判断是否为收件邮件（inbox） */
const isInboxEmail = (email: EmailRecord): boolean => {
  return ["delivered", "read", "draft_replied", "replied"].includes(email.status);
};

/** 判断是否为已发送邮件（sent） */
const isSentEmail = (email: EmailRecord): boolean => {
  return ["sent", "sending", "draft", "failed"].includes(email.status);
};

export function EmailWorkbench() {
  const { toast } = useToast();
  const [currentView, setCurrentView] = useState<ViewType>("inbox");
  const [emails, setEmails] = useState<EmailRecord[]>([]);
  const [loading, setLoading] = useState(false);
  const [fetching, setFetching] = useState(false); // 手动拉取邮件
  const [selectedEmail, setSelectedEmail] = useState<EmailRecord | null>(null);
  const [activeCategory, setActiveCategory] = useState<string | null>(null);
  const [categoryCounts, setCategoryCounts] = useState<Record<string, number>>({});
  const [draftCount, setDraftCount] = useState(0);
  const [editingDraftId, setEditingDraftId] = useState<string | null>(null);
  const [editingReplyTo, setEditingReplyTo] = useState<string | null>(null);

  // 写邮件表单状态
  const [composeTo, setComposeTo] = useState("");
  const [composeSubject, setComposeSubject] = useState("");
  const [composeBody, setComposeBody] = useState("");
  const [composeCategory, setComposeCategory] = useState<string>("");
  const [sending, setSending] = useState(false);

  /**
   * 获取草稿数量
   */
  const fetchDraftCount = useCallback(async () => {
    try {
      const { count, error } = await supabase
        .from("emails")
        .select("*", { count: "exact", head: true })
        .eq("status", "draft");

      if (error) throw error;
      setDraftCount(count || 0);
    } catch (error) {
      console.error("获取草稿数量失败:", error);
    }
  }, []);

  /**
   * 从 emails 表获取邮件列表
   * inbox = status 为 delivered / read / draft_replied / replied
   * sent  = status 为 sent / sending / failed
   * drafts = status 为 draft
   */
  const fetchEmails = useCallback(
    async (view: "inbox" | "sent" | "drafts") => {
      setLoading(true);
      try {
        let query = supabase.from("emails").select("*");

        // 按视图过滤
        if (view === "inbox") {
          query = query.in("status", ["delivered", "read", "draft_replied", "replied"]);
        } else if (view === "drafts") {
          query = query.eq("status", "draft");
        } else {
          // sent: 排除 draft
          query = query.in("status", ["sent", "sending", "failed"]);
        }

        // 按分类过滤（存在 metadata.category 中）
        if (activeCategory) {
          query = query.eq("metadata->>category", activeCategory);
        }

        // 按时间倒序
        query = query.order("created_at", { ascending: false });

        const { data, error } = await query;
        if (error) throw error;
        setEmails((data as EmailRecord[]) || []);
      } catch (error) {
        console.error("获取邮件失败:", error);
        toast({
          title: "错误",
          description: "获取邮件列表失败",
          variant: "destructive",
        });
      } finally {
        setLoading(false);
      }
    },
    [toast, activeCategory]
  );

  /**
   * 获取各分类的邮件数量（不按分类过滤，统计所有分类）
   */
  const fetchCategoryCounts = useCallback(async (view: "inbox" | "sent" | "drafts") => {
    try {
      let query = supabase.from("emails").select("id, metadata");

      if (view === "inbox") {
        query = query.in("status", ["delivered", "read", "draft_replied", "replied"]);
      } else if (view === "drafts") {
        query = query.eq("status", "draft");
      } else {
        // sent: 排除 draft
        query = query.in("status", ["sent", "sending", "failed"]);
      }

      const { data, error } = await query;
      if (error) throw error;

      // 按 category 分组计数
      const counts: Record<string, number> = {};
      (data || []).forEach((email: any) => {
        const category = email.metadata?.category || "other";
        counts[category] = (counts[category] || 0) + 1;
      });
      setCategoryCounts(counts);
    } catch (error) {
      console.error("获取分类计数失败:", error);
    }
  }, []);

  useEffect(() => {
    if (currentView === "inbox" || currentView === "sent" || currentView === "drafts") {
      fetchEmails(currentView);
      fetchCategoryCounts(currentView);
      fetchDraftCount();
      setSelectedEmail(null);
    }
  }, [currentView, fetchEmails, fetchCategoryCounts, fetchDraftCount]);

  /**
   * 手动拉取邮件：调用 fetch-email Edge Function
   */
  const handleFetchEmails = async () => {
    setFetching(true);
    try {
      const supabaseUrl = import.meta.env.VITE_SUPABASE_URL;
      const response = await fetch(`${supabaseUrl}/functions/v1/email-fetch`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ limit: 10 }),
      });

      const result = await response.json();

      if (result.success) {
        toast({
          title: "拉取成功",
          description: `新增 ${result.new_emails} 封邮件，重复 ${result.duplicates} 封`,
        });
        // 刷新列表和计数
        if (currentView === "inbox" || currentView === "sent") {
          fetchEmails(currentView);
          fetchCategoryCounts(currentView);
        }
      } else if (result.errors?.length > 0) {
        toast({
          title: "部分失败",
          description: `新增 ${result.new_emails} 封，${result.errors.length} 个错误`,
          variant: "destructive",
        });
        // 即使有错误也刷新列表和计数（可能有部分成功）
        if (currentView === "inbox" || currentView === "sent") {
          fetchEmails(currentView);
          fetchCategoryCounts(currentView);
        }
      } else {
        toast({
          title: "拉取失败",
          description: result.error || "未知错误",
          variant: "destructive",
        });
      }
    } catch (error) {
      console.error("拉取邮件失败:", error);
      toast({
        title: "错误",
        description: "拉取邮件失败",
        variant: "destructive",
      });
    } finally {
      setFetching(false);
    }
  };

  /** 发送邮件 */
  const handleSendEmail = async () => {
    if (!composeTo) {
      toast({ title: "错误", description: "请输入收件人邮箱", variant: "destructive" });
      return;
    }
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(composeTo)) {
      toast({ title: "错误", description: "请输入有效的邮箱地址", variant: "destructive" });
      return;
    }
    if (!composeSubject) {
      toast({ title: "错误", description: "请输入邮件主题", variant: "destructive" });
      return;
    }
    if (!composeBody) {
      toast({ title: "错误", description: "请输入邮件正文", variant: "destructive" });
      return;
    }

    setSending(true);
    try {
      const { data: { user } } = await supabase.auth.getUser();
      if (!user) throw new Error("未登录");

      const htmlBody = composeBody.replace(/\n/g, "<br/>");
      let draftId = editingDraftId;

      // 1. 如果是新邮件（不是编辑草稿），先保存为草稿
      if (!draftId) {
        const { data: newDraft, error: insertError } = await supabase
          .from("emails")
          .insert([{
            user_id: user.id,
            from_email: user.email || "system@store.com",
            to_email: composeTo,
            subject: composeSubject,
            body_text: composeBody,
            body_html: htmlBody,
            status: "draft",
            in_reply_to: editingReplyTo,
            metadata: {
              category: composeCategory || null,
              source: "compose",
            },
          }])
          .select("id")
          .single();

        if (insertError) throw insertError;
        draftId = newDraft.id;
      } else {
        // 编辑草稿：更新草稿内容
        const { error: updateError } = await supabase
          .from("emails")
          .update({
            to_email: composeTo,
            subject: composeSubject,
            body_text: composeBody,
            body_html: htmlBody,
            in_reply_to: editingReplyTo,
            metadata: {
              category: composeCategory || null,
              source: "compose",
            },
          })
          .eq("id", draftId);

        if (updateError) throw updateError;
      }

      // 2. 调用 email-send-business Edge Function 真正发送邮件
      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: draftId }),
      });

      const sendResult = await sendResponse.json();

      if (!sendResult.success) {
        throw new Error(sendResult.error || "邮件发送失败");
      }

      toast({ title: "成功", description: "邮件发送成功" });

      // 清空表单
      setComposeTo("");
      setComposeSubject("");
      setComposeBody("");
      setComposeCategory("");
      setEditingDraftId(null);
      setEditingReplyTo(null);
      setCurrentView("sent");
      fetchDraftCount();
    } catch (error) {
      console.error("发送邮件失败:", error);
      toast({
        title: "错误",
        description: error instanceof Error ? error.message : "邮件发送失败",
        variant: "destructive",
      });
    } finally {
      setSending(false);
    }
  };

  /** 保存草稿 */
  const handleSaveDraft = async () => {
    if (!composeTo && !composeSubject && !composeBody) {
      toast({ title: "提示", description: "草稿内容为空，未保存", variant: "destructive" });
      return;
    }

    setSending(true);
    try {
      const { data: { user } } = await supabase.auth.getUser();
      if (!user) throw new Error("未登录");

      const draftData = {
        user_id: user.id,
        from_email: user.email || "system@store.com",
        to_email: composeTo,
        subject: composeSubject || "(无主题)",
        body_text: composeBody,
        body_html: composeBody.replace(/\n/g, "<br/>"),
        status: "draft",
        metadata: {
          category: composeCategory || null,
          source: "compose",
        },
      };

      if (editingDraftId) {
        // 更新现有草稿
        const { error } = await supabase
          .from("emails")
          .update(draftData)
          .eq("id", editingDraftId);
        if (error) throw error;
      } else {
        // 创建新草稿
        const { error } = await supabase.from("emails").insert([draftData]);
        if (error) throw error;
      }

      toast({ title: "成功", description: "草稿已保存" });

      // 清空表单并跳转到草稿箱
      setComposeTo("");
      setComposeSubject("");
      setComposeBody("");
      setComposeCategory("");
      setEditingDraftId(null);
      setEditingReplyTo(null);
      setCurrentView("drafts");
      fetchDraftCount();
    } catch (error) {
      console.error("保存草稿失败:", error);
      toast({
        title: "错误",
        description: error instanceof Error ? error.message : "保存草稿失败",
        variant: "destructive",
      });
    } finally {
      setSending(false);
    }
  };

  /** 编辑草稿 */
  const handleEditDraft = (email: EmailRecord) => {
    setComposeTo(email.to_email);
    setComposeSubject(email.subject);
    setComposeBody(email.body_text || "");
    setComposeCategory(email.metadata?.category || "");
    setEditingDraftId(email.id);
    setEditingReplyTo(email.in_reply_to);
    setSelectedEmail(email);
  };

  /** 标记已读 */
  const handleMarkAsRead = async (email: EmailRecord) => {
    if (email.status === "delivered") {
      try {
        await supabase
          .from("emails")
          .update({ status: "read", read_at: new Date().toISOString() })
          .eq("id", email.id);
        setEmails((prev) =>
          prev.map((e) =>
            e.id === email.id
              ? { ...e, status: "read", read_at: new Date().toISOString() }
              : e
          )
        );
        // 更新选中邮件的状态
        setSelectedEmail({ ...email, status: "read", read_at: new Date().toISOString() });
      } catch (error) {
        console.error("标记已读失败:", error);
        setSelectedEmail(email);
      }
    } else {
      setSelectedEmail(email);
    }
  };

  /** 删除邮件 */
  const handleDeleteEmail = async (id: string) => {
    try {
      const { error } = await supabase.from("emails").delete().eq("id", id);
      if (error) throw error;
      setEmails((prev) => prev.filter((e) => e.id !== id));
      if (selectedEmail?.id === id) setSelectedEmail(null);
      // 刷新计数
      if (currentView === "inbox" || currentView === "sent" || currentView === "drafts") {
        fetchCategoryCounts(currentView);
      }
      // 如果是草稿，刷新草稿数量
      if (currentView === "drafts") {
        fetchDraftCount();
      }
      toast({ title: "成功", description: "邮件已删除" });
    } catch (error) {
      console.error("删除邮件失败:", error);
      toast({ title: "错误", description: "删除邮件失败", variant: "destructive" });
    }
  };

  const handleCategoryChange = (categoryId: string | null) => {
    setActiveCategory(categoryId);
    setSelectedEmail(null);
  };

  // 未读数 = inbox 中 status 为 delivered 的邮件
  const unreadCount = emails.filter((e) => isInboxEmail(e) && e.status === "delivered").length;

  // 各分类邮件总数
  const totalEmailCount = Object.values(categoryCounts).reduce((sum, count) => sum + count, 0);

  const navItems: { id: ViewType; label: string; icon: React.ReactNode; badge?: number }[] = [
    { id: "inbox", label: "收件箱", icon: <Inbox className="h-4 w-4" />, badge: currentView === "inbox" ? unreadCount : undefined },
    { id: "sent", label: "已发送", icon: <SendHorizonal className="h-4 w-4" /> },
    { id: "drafts", label: "草稿箱", icon: <FileEdit className="h-4 w-4" />, badge: draftCount > 0 ? draftCount : undefined },
    { id: "compose", label: "写邮件", icon: <Pencil className="h-4 w-4" /> },
  ];

  return (
    <div className="flex flex-col h-full w-full overflow-hidden">
      {/* 顶部导航标签 */}
      <div className="flex items-center justify-between border-b border-border/60 pb-3 mb-0">
        <div className="flex items-center gap-1">
          {navItems.map((item) => (
            <button
              key={item.id}
              onClick={() => setCurrentView(item.id)}
              className={cn(
                "flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-colors",
                currentView === item.id
                  ? "bg-primary/10 text-primary"
                  : "text-muted-foreground hover:text-foreground hover:bg-muted/50"
              )}
            >
              {item.icon}
              <span>{item.label}</span>
              {item.badge !== undefined && item.badge > 0 && (
                <Badge variant="destructive" className="h-5 min-w-[20px] px-1.5 text-[10px]">
                  {item.badge}
                </Badge>
              )}
            </button>
          ))}
        </div>
        <div className="flex items-center gap-1">
          {/* 手动拉取邮件按钮 */}
          {currentView === "inbox" && (
            <Button
              variant="ghost"
              size="sm"
              onClick={handleFetchEmails}
              disabled={fetching || loading}
              className="text-xs"
            >
              <Download className={cn("h-4 w-4 mr-1", fetching && "animate-bounce")} />
              拉取邮件
            </Button>
          )}
          <Button
            variant="ghost"
            size="sm"
            onClick={() => {
              if (currentView === "inbox" || currentView === "sent") {
                fetchEmails(currentView);
              }
            }}
            disabled={loading || currentView === "compose"}
          >
            <RefreshCw className={cn("h-4 w-4", loading && "animate-spin")} />
          </Button>
        </div>
      </div>

      {/* 分类导航 */}
      {currentView !== "compose" && (
        <div className="flex items-center gap-1.5 py-2.5 border-b border-border/40 overflow-x-auto shrink-0">
          <button
            onClick={() => handleCategoryChange(null)}
            className={cn(
              "flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-medium whitespace-nowrap transition-colors shrink-0",
              activeCategory === null
                ? "bg-foreground text-background"
                : "text-muted-foreground hover:text-foreground hover:bg-muted/60"
            )}
          >
            <LayoutGrid className="h-3 w-3" />
            全部
            {totalEmailCount > 0 && (
              <span className={cn(
                "text-[10px] min-w-[16px] h-4 px-1 rounded-full flex items-center justify-center",
                activeCategory === null
                  ? "bg-background/20 text-background"
                  : "bg-muted text-muted-foreground"
              )}>
                {totalEmailCount}
              </span>
            )}
          </button>
          {CATEGORIES.map((cat) => {
            const count = categoryCounts[cat.id] || 0;
            return (
              <button
                key={cat.id}
                onClick={() => handleCategoryChange(cat.id)}
                className={cn(
                  "flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-medium whitespace-nowrap transition-colors shrink-0",
                  activeCategory === cat.id
                    ? "bg-foreground text-background"
                    : "text-muted-foreground hover:text-foreground hover:bg-muted/60"
                )}
              >
                <span className={cn(activeCategory === cat.id ? "" : cat.color)}>{cat.icon}</span>
                {cat.label}
                {count > 0 && (
                  <span className={cn(
                    "text-[10px] min-w-[16px] h-4 px-1 rounded-full flex items-center justify-center",
                    activeCategory === cat.id
                      ? "bg-background/20 text-background"
                      : "bg-muted text-muted-foreground"
                  )}>
                    {count}
                  </span>
                )}
              </button>
            );
          })}
        </div>
      )}

      {/* 内容区域 */}
      <div className="flex-1 min-h-0 overflow-hidden pt-4 flex flex-col">
        {currentView === "compose" ? (
          /* 写邮件 */
          <Card className="flex-1 flex flex-col min-h-0">
            <CardHeader className="pb-3">
              <div className="flex items-center gap-3">
                <div className="h-10 w-10 rounded-lg bg-primary/10 flex items-center justify-center">
                  <Pencil className="h-5 w-5 text-primary" />
                </div>
                <CardTitle className="text-lg">{editingDraftId ? "编辑草稿" : "写邮件"}</CardTitle>
              </div>
            </CardHeader>
            <CardContent className="space-y-4 flex-1 flex flex-col min-h-0">
              <div className="flex items-center gap-3">
                <label className="text-sm font-medium text-muted-foreground shrink-0 w-16">收件人</label>
                <Input
                  type="email"
                  placeholder="请输入收件人邮箱地址"
                  value={composeTo}
                  onChange={(e) => setComposeTo(e.target.value)}
                  className="flex-1"
                />
                <label className="text-sm font-medium text-muted-foreground shrink-0 w-12">分类</label>
                <Select value={composeCategory} onValueChange={setComposeCategory}>
                  <SelectTrigger className="w-40">
                    <SelectValue placeholder="选择分类" />
                  </SelectTrigger>
                  <SelectContent>
                    {CATEGORIES.map((cat) => (
                      <SelectItem key={cat.id} value={cat.id}>
                        <div className="flex items-center gap-2">
                          <span className={cat.color}>{cat.icon}</span>
                          {cat.label}
                        </div>
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="flex items-center gap-3">
                <label className="text-sm font-medium text-muted-foreground shrink-0 w-16">主题</label>
                <Input
                  placeholder="请输入邮件主题"
                  value={composeSubject}
                  onChange={(e) => setComposeSubject(e.target.value)}
                  className="flex-1"
                />
              </div>
              <div className="flex-1 flex flex-col min-h-0">
                <label className="text-sm font-medium text-muted-foreground mb-1.5 block">正文</label>
                <Textarea
                  placeholder="请输入邮件正文..."
                  value={composeBody}
                  onChange={(e) => setComposeBody(e.target.value)}
                  className="flex-1 resize-none min-h-0"
                />
              </div>
              <div className="flex justify-end gap-3 pt-2">
                <Button variant="outline" onClick={() => {
                  setEditingDraftId(null);
                  setEditingReplyTo(null);
                  setComposeTo("");
                  setComposeSubject("");
                  setComposeBody("");
                  setComposeCategory("");
                  setCurrentView("inbox");
                }}>
                  取消
                </Button>
                <Button variant="secondary" onClick={handleSaveDraft} disabled={sending}>
                  {sending ? (
                    <>
                      <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                      保存中...
                    </>
                  ) : (
                    <>
                      <FileEdit className="h-4 w-4 mr-2" />
                      保存草稿
                    </>
                  )}
                </Button>
                <Button onClick={handleSendEmail} disabled={sending} className="min-w-[120px]">
                  {sending ? (
                    <>
                      <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                      发送中...
                    </>
                  ) : (
                    <>
                      <Send className="h-4 w-4 mr-2" />
                      发送邮件
                    </>
                  )}
                </Button>
              </div>
            </CardContent>
          </Card>
        ) : (
          /* 收件箱 / 已发送 / 草稿箱 */
          <div className="flex gap-4 flex-1 min-h-0 min-w-0">
            {/* 邮件列表 */}
            <div className="w-[380px] shrink-0 min-w-0 min-h-0 border border-border/60 rounded-lg flex flex-col overflow-hidden">
              <div className="flex-1 min-h-0 overflow-y-auto">
                {loading ? (
                  <div className="flex items-center justify-center py-12">
                    <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
                  </div>
                ) : emails.length === 0 ? (
                  <div className="flex flex-col items-center justify-center py-12 text-muted-foreground">
                    <Mail className="h-10 w-10 mb-3 opacity-40" />
                    <p className="text-sm">
                      {activeCategory
                        ? `暂无「${getCategoryById(activeCategory)?.label}」分类的邮件`
                        : currentView === "inbox"
                          ? "收件箱为空"
                          : currentView === "drafts"
                            ? "草稿箱为空"
                            : "暂无已发送邮件"}
                    </p>
                    {currentView === "inbox" && (
                      <Button
                        variant="outline"
                        size="sm"
                        className="mt-3"
                        onClick={handleFetchEmails}
                        disabled={fetching}
                      >
                        <Download className={cn("h-4 w-4 mr-1", fetching && "animate-bounce")} />
                        拉取邮件
                      </Button>
                    )}
                  </div>
                ) : (
                  <div className="divide-y divide-border/40">
                    {emails.map((email) => {
                      const cat = getCategoryById(getEmailCategory(email));
                      const body = getEmailBody(email);
                      const time = getEmailTime(email);
                      const isUnread = email.status === "delivered";

                      return (
                        <button
                          key={email.id}
                          onClick={() => {
                            if (currentView === "drafts") {
                              handleEditDraft(email);
                            } else {
                              handleMarkAsRead(email);
                            }
                          }}
                          className={cn(
                            "w-full text-left px-4 py-3 transition-colors hover:bg-muted/40",
                            selectedEmail?.id === email.id && "bg-primary/5 border-l-2 border-l-primary",
                            isUnread && "bg-primary/[0.02]"
                          )}
                        >
                          <div className="flex items-start gap-3">
                            <div className="mt-0.5 shrink-0">
                              {currentView === "drafts" ? (
                                <FileEdit className="h-4 w-4 text-muted-foreground" />
                              ) : email.status === "draft_replied" ? (
                                <MessageSquare className="h-4 w-4 text-cyan-600" />
                              ) : email.status === "replied" ? (
                                <Reply className="h-4 w-4 text-green-600" />
                              ) : isUnread ? (
                                <Mail className="h-4 w-4 text-primary" />
                              ) : (
                                <MailOpen className="h-4 w-4 text-muted-foreground" />
                              )}
                            </div>
                            <div className="flex-1 min-w-0">
                              <div className="flex items-center justify-between gap-2">
                                <p
                                  className={cn(
                                    "text-sm truncate",
                                    isUnread ? "font-semibold" : "font-medium"
                                  )}
                                >
                                  {currentView === "inbox" ? email.from_email : email.to_email}
                                </p>
                                <div className="flex items-center gap-1 shrink-0">
                                  {email.has_attachments && (
                                    <Paperclip className="h-3 w-3 text-muted-foreground" />
                                  )}
                                  <span className="text-[10px] text-muted-foreground">
                                    {format(new Date(time), "MM/dd HH:mm", { locale: zhCN })}
                                  </span>
                                </div>
                              </div>
                              <div className="flex items-center gap-1.5 mt-0.5">
                                <p className="text-sm truncate flex-1">{email.subject || "(无主题)"}</p>
                                {email.status === "draft_replied" && (
                                  <span className="shrink-0 inline-flex items-center gap-1 text-[10px] px-1.5 py-0.5 rounded-full bg-cyan-100 text-cyan-700">
                                    <MessageSquare className="h-3 w-3" />
                                    已草稿
                                  </span>
                                )}
                                {email.status === "replied" && (
                                  <span className="shrink-0 inline-flex items-center gap-1 text-[10px] px-1.5 py-0.5 rounded-full bg-green-100 text-green-700">
                                    <Reply className="h-3 w-3" />
                                    已回复
                                  </span>
                                )}
                                {cat && (
                                  <span
                                    className={cn(
                                      "shrink-0 inline-flex items-center gap-1 text-[10px] px-1.5 py-0.5 rounded-full bg-muted",
                                      cat.color
                                    )}
                                  >
                                    {cat.icon}
                                    {cat.label}
                                  </span>
                                )}
                              </div>
                              <p className="text-xs text-muted-foreground truncate mt-0.5">
                                {body.slice(0, 60)}
                              </p>
                            </div>
                          </div>
                        </button>
                      );
                    })}
                  </div>
                )}
              </div>
            </div>

            {/* 邮件详情/编辑 */}
            <div className="flex-1 min-w-0 min-h-0 w-0 border border-border/60 rounded-lg flex flex-col overflow-hidden">
              {selectedEmail ? (
                currentView === "drafts" ? (
                  /* 草稿箱：可编辑表单 */
                  <>
                    <div className="border-b border-border/40 px-5 py-3 shrink-0 flex items-center justify-between">
                      <div className="flex items-center gap-2">
                        <FileEdit className="h-5 w-5 text-amber-600" />
                        <h3 className="font-semibold text-base">编辑草稿</h3>
                      </div>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={async () => {
                          if (!selectedEmail) return;
                          if (!confirm("确定删除这封草稿吗？")) return;
                          await handleDeleteEmail(selectedEmail.id);
                        }}
                        className="text-muted-foreground hover:text-destructive"
                      >
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </div>
                    <div className="flex-1 min-h-0 flex flex-col px-5 py-4 gap-3">
                      <div className="flex items-center gap-3 shrink-0">
                        <label className="text-sm font-medium text-muted-foreground shrink-0 w-16">收件人</label>
                        <Input
                          type="email"
                          placeholder="请输入收件人邮箱地址"
                          value={composeTo}
                          onChange={(e) => setComposeTo(e.target.value)}
                          className="flex-1"
                        />
                        <label className="text-sm font-medium text-muted-foreground shrink-0 w-12">分类</label>
                        <Select value={composeCategory} onValueChange={setComposeCategory}>
                          <SelectTrigger className="w-40">
                            <SelectValue placeholder="选择分类" />
                          </SelectTrigger>
                          <SelectContent>
                            {CATEGORIES.map((cat) => (
                              <SelectItem key={cat.id} value={cat.id}>
                                <div className="flex items-center gap-2">
                                  <span className={cat.color}>{cat.icon}</span>
                                  {cat.label}
                                </div>
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>
                      <div className="flex items-center gap-3 shrink-0">
                        <label className="text-sm font-medium text-muted-foreground shrink-0 w-16">主题</label>
                        <Input
                          placeholder="请输入邮件主题"
                          value={composeSubject}
                          onChange={(e) => setComposeSubject(e.target.value)}
                          className="flex-1"
                        />
                      </div>
                      <Textarea
                        placeholder="请输入邮件正文..."
                        value={composeBody}
                        onChange={(e) => setComposeBody(e.target.value)}
                        className="flex-1 min-h-0 resize-none"
                      />
                    </div>
                    <div className="border-t border-border/40 px-5 py-3 flex justify-end gap-3 shrink-0">
                      <Button variant="outline" onClick={() => {
                        setSelectedEmail(null);
                        setEditingDraftId(null);
                        setEditingReplyTo(null);
                        setComposeTo("");
                        setComposeSubject("");
                        setComposeBody("");
                        setComposeCategory("");
                      }}>
                        取消
                      </Button>
                      <Button variant="secondary" onClick={handleSaveDraft} disabled={sending}>
                        {sending ? (
                          <>
                            <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                            保存中...
                          </>
                        ) : (
                          <>
                            <FileEdit className="h-4 w-4 mr-2" />
                            保存草稿
                          </>
                        )}
                      </Button>
                      <Button onClick={handleSendEmail} disabled={sending} className="min-w-[120px]">
                        {sending ? (
                          <>
                            <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                            发送中...
                          </>
                        ) : (
                          <>
                            <Send className="h-4 w-4 mr-2" />
                            发送邮件
                          </>
                        )}
                      </Button>
                    </div>
                  </>
                ) : (
                  /* 收件箱/已发送：只读详情 */
                  <>
                    {/* 详情头部 */}

                    <div className="border-b border-border/40 px-5 py-4 flex items-start justify-between gap-4 shrink-0 min-w-0">
                      <div className="min-w-0">
                        <div className="flex items-center gap-2 min-w-0">
                          <h3 className="font-semibold text-base truncate min-w-0">{selectedEmail.subject || "(无主题)"}</h3>
                          {getCategoryById(getEmailCategory(selectedEmail)) && (
                            <span
                              className={cn(
                                "shrink-0 inline-flex items-center gap-1 text-xs px-2 py-0.5 rounded-full bg-muted",
                                getCategoryById(getEmailCategory(selectedEmail))!.color
                              )}
                            >
                              {getCategoryById(getEmailCategory(selectedEmail))!.icon}
                              {getCategoryById(getEmailCategory(selectedEmail))!.label}
                            </span>
                          )}
                        </div>
                        <div className="flex items-center gap-2 mt-1.5 text-sm text-muted-foreground min-w-0 overflow-hidden">
                          {currentView === "inbox" ? (
                            <>
                              <span className="truncate">来自: {selectedEmail.from_email}</span>
                              <span className="shrink-0">·</span>
                              <span className="truncate">发送至: {selectedEmail.to_email}</span>
                            </>
                          ) : (
                            <span className="truncate">发送至: {selectedEmail.to_email}</span>
                          )}
                          {selectedEmail.cc_emails && selectedEmail.cc_emails.length > 0 && (
                            <>
                              <span className="shrink-0">·</span>
                              <span className="truncate" title={selectedEmail.cc_emails.join(", ")}>
                                抄送: {selectedEmail.cc_emails.join(", ")}
                              </span>
                            </>
                          )}
                        </div>
                        <p className="text-xs text-muted-foreground mt-1">
                          {format(new Date(getEmailTime(selectedEmail)), "yyyy-MM-dd HH:mm:ss", { locale: zhCN })}
                        </p>
                      </div>
                    <div className="flex items-center gap-2 shrink-0">
                      {selectedEmail.status === "sent" && (
                        <Badge variant="outline" className="text-emerald-600 border-emerald-200">
                          <MailCheck className="h-3 w-3 mr-1" />
                          已送达
                        </Badge>
                      )}
                      {selectedEmail.status === "sending" && (
                        <Badge variant="outline" className="text-amber-600 border-amber-200">
                          <Loader2 className="h-3 w-3 mr-1 animate-spin" />
                          发送中
                        </Badge>
                      )}
                      {selectedEmail.status === "failed" && (
                        <Badge variant="destructive">
                          <AlertCircle className="h-3 w-3 mr-1" />
                          发送失败
                        </Badge>
                      )}
                      {selectedEmail.status === "delivered" && (
                        <Badge variant="outline" className="text-blue-600 border-blue-200">
                          <Mail className="h-3 w-3 mr-1" />
                          未读
                        </Badge>
                      )}
                      {selectedEmail.status === "read" && (
                        <Badge variant="outline" className="text-gray-500 border-gray-200">
                          <MailOpen className="h-3 w-3 mr-1" />
                          已读
                        </Badge>
                      )}
                      {selectedEmail.status === "draft" && (
                        <Badge variant="outline" className="text-amber-600 border-amber-200">
                          <FileEdit className="h-3 w-3 mr-1" />
                          草稿
                        </Badge>
                      )}
                      {selectedEmail.status === "draft_replied" && (
                        <Badge variant="outline" className="text-cyan-600 border-cyan-200">
                          <MessageSquare className="h-3 w-3 mr-1" />
                          已草稿
                        </Badge>
                      )}
                      {selectedEmail.status === "replied" && (
                        <Badge variant="outline" className="text-green-600 border-green-200">
                          <Reply className="h-3 w-3 mr-1" />
                          已回复
                        </Badge>
                      )}
                      {currentView === "drafts" && (
                        <>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleEditDraft(selectedEmail)}
                            className="text-primary hover:text-primary"
                          >
                            <FileEdit className="h-4 w-4 mr-1" />
                            编辑
                          </Button>
                          <Button
                            variant="default"
                            size="sm"
                            onClick={async () => {
                              if (!selectedEmail) return;
                              setSending(true);
                              try {
                                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: selectedEmail.id }),
                                });
                                const sendResult = await sendResponse.json();
                                if (!sendResult.success) {
                                  throw new Error(sendResult.error || "发送失败");
                                }
                                toast({ title: "成功", description: "邮件发送成功" });
                                setSelectedEmail(null);
                                fetchDraftCount();
                                fetchEmails("drafts");
                              } catch (error) {
                                console.error("发送邮件失败:", error);
                                toast({
                                  title: "错误",
                                  description: error instanceof Error ? error.message : "发送失败",
                                  variant: "destructive",
                                });
                              } finally {
                                setSending(false);
                              }
                            }}
                            disabled={sending}
                          >
                            {sending ? (
                              <>
                                <Loader2 className="h-4 w-4 mr-1 animate-spin" />
                                发送中...
                              </>
                            ) : (
                              <>
                                <Send className="h-4 w-4 mr-1" />
                                发送
                              </>
                            )}
                          </Button>
                        </>
                      )}
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleDeleteEmail(selectedEmail.id)}
                        className="text-muted-foreground hover:text-destructive"
                      >
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </div>
                  </div>
                  {/* 详情正文 */}
                  <div className="flex-1 overflow-y-auto overflow-x-hidden px-5 py-4 min-w-0">
                    {/* 附件列表 */}
                    {selectedEmail.has_attachments && selectedEmail.attachments && selectedEmail.attachments.length > 0 && (
                      <div className="mb-4 pb-3 border-b border-border/40">
                        <div className="flex items-center gap-1.5 text-sm font-medium text-muted-foreground mb-2">
                          <Paperclip className="h-3.5 w-3.5" />
                          附件 ({selectedEmail.attachments.length})
                        </div>
                        <div className="flex flex-wrap gap-2">
                          {selectedEmail.attachments.map((att, i) => (
                            <span
                              key={i}
                              className="inline-flex items-center gap-1 text-xs px-2 py-1 rounded bg-muted text-muted-foreground"
                            >
                              {att.filename}
                              <span className="text-[10px] opacity-60">
                                ({(att.size / 1024).toFixed(0)}KB)
                              </span>
                            </span>
                          ))}
                        </div>
                      </div>
                    )}
                    {/* 邮件正文 */}
                    {selectedEmail.body_html ? (
                      <div
                        className="text-sm leading-relaxed prose prose-sm max-w-full break-words overflow-hidden [&_img]:max-w-full [&_table]:max-w-full [&_table]:block"
                        dangerouslySetInnerHTML={{ __html: selectedEmail.body_html }}
                      />
                    ) : (
                      <div className="text-sm whitespace-pre-wrap leading-relaxed break-words">
                        {getEmailBody(selectedEmail)}
                      </div>
                    )}
                  </div>
                </>
                )
              ) : (
                <div className="flex-1 flex flex-col items-center justify-center text-muted-foreground">
                  <Eye className="h-10 w-10 mb-3 opacity-40" />
                  <p className="text-sm">
                    {currentView === "drafts" ? "选择一封草稿进行编辑" : "选择一封邮件查看详情"}
                  </p>
                </div>
              )}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
