"use client";

import React, { useEffect, useState } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
  X,
  Paperclip,
  Reply,
  Forward,
  Loader2,
  AlertCircle,
} from "lucide-react";
import { MailDetail, getMailDetail, markMailAsRead } from "@/lib/api/mail";
import DOMPurify from "isomorphic-dompurify";

interface MailDetailModalProps {
  isOpen: boolean;
  onClose: () => void;
  accountId: string;
  mailId: string; // "accountId-seqno" 형식
  onMailRead?: () => void; // 읽음 처리 후 목록 갱신용
}

export default function MailDetailModal({
  isOpen,
  onClose,
  accountId,
  mailId,
  onMailRead,
}: MailDetailModalProps) {
  const [mail, setMail] = useState<MailDetail | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [showHtml, setShowHtml] = useState(true); // HTML/텍스트 토글

  useEffect(() => {
    if (isOpen && mailId) {
      loadMailDetail();
    }
  }, [isOpen, mailId]);

  const loadMailDetail = async () => {
    setLoading(true);
    setError(null);

    try {
      // mailId에서 seqno 추출 (예: "account123-45" -> 45)
      const seqno = parseInt(mailId.split("-").pop() || "0", 10);

      if (isNaN(seqno)) {
        throw new Error("유효하지 않은 메일 ID입니다.");
      }

      // 메일 상세 조회
      const mailDetail = await getMailDetail(accountId, seqno);
      setMail(mailDetail);

      // 읽음 처리
      if (!mailDetail.isRead) {
        await markMailAsRead(accountId, seqno);
        onMailRead?.(); // 목록 갱신
      }
    } catch (err) {
      console.error("메일 상세 조회 실패:", err);
      setError(
        err instanceof Error
          ? err.message
          : "메일을 불러오는데 실패했습니다."
      );
    } finally {
      setLoading(false);
    }
  };

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleString("ko-KR", {
      year: "numeric",
      month: "long",
      day: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    });
  };

  const formatFileSize = (bytes: number) => {
    if (bytes < 1024) return `${bytes} B`;
    if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
    return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
  };

  const sanitizeHtml = (html: string) => {
    return DOMPurify.sanitize(html, {
      ALLOWED_TAGS: [
        "p",
        "br",
        "strong",
        "em",
        "u",
        "a",
        "ul",
        "ol",
        "li",
        "h1",
        "h2",
        "h3",
        "h4",
        "h5",
        "h6",
        "img",
        "div",
        "span",
        "table",
        "tr",
        "td",
        "th",
        "thead",
        "tbody",
      ],
      ALLOWED_ATTR: ["href", "src", "alt", "title", "style", "class"],
    });
  };

  const handleDownloadAttachment = async (index: number, filename: string) => {
    try {
      const seqno = parseInt(mailId.split("-").pop() || "0", 10);
      
      // 다운로드 URL
      const downloadUrl = `http://localhost:8080/api/mail/receive/${accountId}/${seqno}/attachment/${index}`;
      
      // 다운로드 트리거
      const link = document.createElement('a');
      link.href = downloadUrl;
      link.download = filename;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    } catch (err) {
      console.error('첨부파일 다운로드 실패:', err);
      alert('첨부파일 다운로드에 실패했습니다.');
    }
  };

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="max-w-4xl max-h-[90vh] overflow-hidden flex flex-col">
        <DialogHeader>
          <DialogTitle className="flex items-center justify-between pr-6">
            <span className="text-xl font-bold truncate">메일 상세</span>
            <Button
              variant="ghost"
              size="sm"
              onClick={onClose}
              className="absolute right-4 top-4"
            >
              <X className="w-4 h-4" />
            </Button>
          </DialogTitle>
        </DialogHeader>

        {loading ? (
          <div className="flex justify-center items-center py-16">
            <Loader2 className="w-8 h-8 animate-spin text-orange-500" />
            <span className="ml-3 text-gray-600">메일을 불러오는 중...</span>
          </div>
        ) : error ? (
          <div className="flex flex-col items-center justify-center py-16">
            <AlertCircle className="w-12 h-12 text-red-500 mb-4" />
            <p className="text-red-600">{error}</p>
            <Button onClick={loadMailDetail} variant="outline" className="mt-4">
              다시 시도
            </Button>
          </div>
        ) : mail ? (
          <div className="flex-1 overflow-y-auto space-y-4">
            {/* 메일 헤더 */}
            <div className="border-b pb-4 space-y-2">
              <h2 className="text-2xl font-bold text-gray-900">
                {mail.subject}
              </h2>
              <div className="flex items-center justify-between">
                <div className="space-y-1 text-sm">
                  <div>
                    <span className="font-medium text-gray-700">보낸사람:</span>{" "}
                    <span className="text-gray-900">{mail.from}</span>
                  </div>
                  <div>
                    <span className="font-medium text-gray-700">받는사람:</span>{" "}
                    <span className="text-gray-600">{mail.to}</span>
                  </div>
                  {mail.cc && (
                    <div>
                      <span className="font-medium text-gray-700">참조:</span>{" "}
                      <span className="text-gray-600">{mail.cc}</span>
                    </div>
                  )}
                  <div>
                    <span className="font-medium text-gray-700">날짜:</span>{" "}
                    <span className="text-gray-600">
                      {formatDate(mail.date)}
                    </span>
                  </div>
                </div>
                <div className="flex gap-2">
                  <Button variant="outline" size="sm">
                    <Reply className="w-4 h-4 mr-2" />
                    답장
                  </Button>
                  <Button variant="outline" size="sm">
                    <Forward className="w-4 h-4 mr-2" />
                    전달
                  </Button>
                </div>
              </div>
            </div>

            {/* 첨부파일 */}
            {mail.attachments && mail.attachments.length > 0 && (
              <div className="bg-gray-50 rounded-lg p-4">
                <div className="flex items-center gap-2 mb-3">
                  <Paperclip className="w-4 h-4 text-gray-600" />
                  <span className="font-medium text-gray-700">
                    첨부파일 ({mail.attachments.length})
                  </span>
                </div>
                <div className="space-y-2">
                  {mail.attachments.map((attachment, index) => (
                    <div
                      key={index}
                      className="flex items-center justify-between bg-white rounded px-3 py-2 border hover:border-orange-300 transition-colors"
                    >
                      <div className="flex items-center gap-2">
                        <Paperclip className="w-4 h-4 text-gray-400" />
                        <span className="text-sm text-gray-900">
                          {attachment.filename}
                        </span>
                        <Badge variant="secondary" className="text-xs">
                          {formatFileSize(attachment.size)}
                        </Badge>
                      </div>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleDownloadAttachment(index, attachment.filename)}
                        className="hover:bg-orange-50 hover:text-orange-600"
                      >
                        다운로드
                      </Button>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {/* HTML/텍스트 토글 */}
            {mail.htmlBody && mail.textBody && (
              <div className="flex gap-2">
                <Button
                  variant={showHtml ? "default" : "outline"}
                  size="sm"
                  onClick={() => setShowHtml(true)}
                  className={
                    showHtml ? "bg-orange-500 hover:bg-orange-600" : ""
                  }
                >
                  HTML 보기
                </Button>
                <Button
                  variant={!showHtml ? "default" : "outline"}
                  size="sm"
                  onClick={() => setShowHtml(false)}
                  className={
                    !showHtml ? "bg-orange-500 hover:bg-orange-600" : ""
                  }
                >
                  텍스트 보기
                </Button>
              </div>
            )}

            {/* 메일 본문 */}
            <div className="border rounded-lg p-6 bg-white min-h-[300px]">
              {showHtml && mail.htmlBody ? (
                <div
                  className="prose max-w-none"
                  dangerouslySetInnerHTML={{
                    __html: sanitizeHtml(mail.htmlBody),
                  }}
                />
              ) : (
                <pre className="whitespace-pre-wrap font-sans text-sm text-gray-800">
                  {mail.textBody || "본문 내용이 없습니다."}
                </pre>
              )}
            </div>
          </div>
        ) : null}
      </DialogContent>
    </Dialog>
  );
}

