"use client";

import React, { useState, useEffect } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Inbox,
  Search,
  Filter,
  Eye,
  Trash2,
  RefreshCw,
  CheckCircle2,
  XCircle,
  Mail,
  Calendar,
  User,
  Paperclip,
  Loader2,
  X,
  File,
  LayoutDashboard,
} from "lucide-react";
import { useRouter } from "next/navigation";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  SentMailHistory,
  getSentMailList,
  deleteSentMail,
  getMailAccounts,
  MailAccount,
} from "@/lib/api/mail";
import { useToast } from "@/hooks/use-toast";

export default function SentMailPage() {
  const router = useRouter();
  const { toast } = useToast();
  const [mails, setMails] = useState<SentMailHistory[]>([]);
  const [accounts, setAccounts] = useState<MailAccount[]>([]);
  const [loading, setLoading] = useState(false);
  const [selectedMail, setSelectedMail] = useState<SentMailHistory | null>(null);

  // 필터 및 페이징
  const [searchTerm, setSearchTerm] = useState("");
  const [filterStatus, setFilterStatus] = useState<'all' | 'success' | 'failed'>('all');
  const [filterAccountId, setFilterAccountId] = useState<string>('all');
  const [sortBy, setSortBy] = useState<'sentAt' | 'subject'>('sentAt');
  const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('desc');
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [total, setTotal] = useState(0);

  useEffect(() => {
    loadAccounts();
    loadMails();
  }, [page, filterStatus, filterAccountId, sortBy, sortOrder]);

  const loadAccounts = async () => {
    try {
      const data = await getMailAccounts();
      setAccounts(data);
    } catch (error: unknown) {
      const err = error as Error;
      toast({
        title: "계정 로드 실패",
        description: err.message,
        variant: "destructive",
      });
    }
  };

  const loadMails = async () => {
    try {
      setLoading(true);
      const result = await getSentMailList({
        page,
        limit: 20,
        searchTerm: searchTerm || undefined,
        status: filterStatus,
        accountId: filterAccountId !== 'all' ? filterAccountId : undefined,
        sortBy,
        sortOrder,
      });

      setMails(result.items);
      setTotalPages(result.totalPages);
      setTotal(result.total);
    } catch (error: unknown) {
      const err = error as Error;
      toast({
        title: "발송 이력 로드 실패",
        description: err.message,
        variant: "destructive",
      });
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = () => {
    setPage(1);
    loadMails();
  };

  const handleDelete = async (id: string) => {
    if (!confirm("이 발송 이력을 삭제하시겠습니까?")) {
      return;
    }

    try {
      await deleteSentMail(id);
      toast({
        title: "삭제 완료",
        description: "발송 이력이 삭제되었습니다.",
      });
      loadMails();
    } catch (error: unknown) {
      const err = error as Error;
      toast({
        title: "삭제 실패",
        description: err.message,
        variant: "destructive",
      });
    }
  };

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

  const formatFileSize = (bytes: number) => {
    if (bytes === 0) return "0 Bytes";
    const k = 1024;
    const sizes = ["Bytes", "KB", "MB"];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return Math.round(bytes / Math.pow(k, i) * 100) / 100 + " " + sizes[i];
  };

  if (loading && page === 1) {
    return (
      <div className="flex items-center justify-center min-h-[60vh]">
        <Loader2 className="w-8 h-8 animate-spin text-primary" />
      </div>
    );
  }

  return (
    <div className="p-6 space-y-6 bg-slate-50 min-h-screen">
      {/* 헤더 */}
      <div className="flex items-center justify-between bg-white rounded-lg shadow-sm border p-6">
        <div>
          <h1 className="text-3xl font-bold text-gray-900 flex items-center gap-2">
            <Inbox className="w-8 h-8" />
            보낸메일함
          </h1>
          <p className="mt-2 text-gray-600">발송된 메일의 이력을 확인하고 관리하세요</p>
        </div>
        <Button 
          variant="outline" 
          size="sm"
          onClick={() => router.push('/admin/mail/dashboard')}
        >
          <LayoutDashboard className="w-4 h-4 mr-2" />
          대시보드
        </Button>
      </div>

      {/* 필터 및 검색 */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Filter className="w-5 h-5" />
            필터 및 검색
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
            {/* 검색 */}
            <div className="md:col-span-2">
              <Label htmlFor="search">검색</Label>
              <div className="flex gap-2">
                <Input
                  id="search"
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
                  placeholder="제목 또는 받는사람 검색..."
                />
                <Button onClick={handleSearch} size="icon">
                  <Search className="w-4 h-4" />
                </Button>
              </div>
            </div>

            {/* 상태 필터 */}
            <div>
              <Label>상태</Label>
              <Select value={filterStatus} onValueChange={(v: any) => {
                setFilterStatus(v);
                setPage(1);
              }}>
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">전체</SelectItem>
                  <SelectItem value="success">성공</SelectItem>
                  <SelectItem value="failed">실패</SelectItem>
                </SelectContent>
              </Select>
            </div>

            {/* 계정 필터 */}
            <div>
              <Label>발송 계정</Label>
              <Select value={filterAccountId} onValueChange={(v) => {
                setFilterAccountId(v);
                setPage(1);
              }}>
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">전체 계정</SelectItem>
                  {accounts.map((account) => (
                    <SelectItem key={account.id} value={account.id}>
                      {account.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>

          <div className="flex items-center justify-between">
            <div className="flex gap-2">
              <Button
                variant="outline"
                size="sm"
                onClick={() => {
                  setSortBy('sentAt');
                  setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc');
                }}
              >
                <Calendar className="w-4 h-4 mr-2" />
                날짜순 {sortBy === 'sentAt' && (sortOrder === 'asc' ? '↑' : '↓')}
              </Button>
              <Button
                variant="outline"
                size="sm"
                onClick={() => {
                  setSortBy('subject');
                  setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc');
                }}
              >
                제목순 {sortBy === 'subject' && (sortOrder === 'asc' ? '↑' : '↓')}
              </Button>
            </div>

            <Button
              variant="outline"
              size="sm"
              onClick={loadMails}
              disabled={loading}
            >
              <RefreshCw className={`w-4 h-4 mr-2 ${loading ? 'animate-spin' : ''}`} />
              새로고침
            </Button>
          </div>
        </CardContent>
      </Card>

      {/* 메일 목록 */}
      <Card>
        <CardHeader>
          <CardTitle>
            발송 이력 ({total}건)
          </CardTitle>
        </CardHeader>
        <CardContent>
          {mails.length === 0 ? (
            <div className="text-center py-12">
              <Mail className="w-16 h-16 mx-auto mb-4 text-gray-300" />
              <p className="text-gray-500">발송된 메일이 없습니다</p>
            </div>
          ) : (
            <div className="space-y-3">
              {mails.map((mail) => (
                <div
                  key={mail.id}
                  className="flex items-center justify-between p-4 border rounded-lg hover:bg-gray-50 transition-colors"
                >
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 mb-1">
                      {mail.status === 'success' ? (
                        <CheckCircle2 className="w-4 h-4 text-green-500 flex-shrink-0" />
                      ) : (
                        <XCircle className="w-4 h-4 text-red-500 flex-shrink-0" />
                      )}
                      <h3 className="font-medium text-gray-900 truncate">
                        {mail.subject}
                      </h3>
                      {mail.attachments && mail.attachments.length > 0 && (
                        <Paperclip className="w-4 h-4 text-gray-400" />
                      )}
                    </div>
                    <div className="flex items-center gap-4 text-sm text-gray-500">
                      <div className="flex items-center gap-1">
                        <User className="w-3 h-3" />
                        <span>{mail.accountName}</span>
                      </div>
                      <div className="flex items-center gap-1">
                        <Mail className="w-3 h-3" />
                        <span>받는사람: {mail.to.length}명</span>
                        {mail.cc && mail.cc.length > 0 && (
                          <span className="text-gray-400">(참조 {mail.cc.length}명)</span>
                        )}
                      </div>
                      <div className="flex items-center gap-1">
                        <Calendar className="w-3 h-3" />
                        <span>{formatDate(mail.sentAt)}</span>
                      </div>
                    </div>
                    {mail.status === 'failed' && mail.errorMessage && (
                      <div className="mt-1 text-sm text-red-600">
                        오류: {mail.errorMessage}
                      </div>
                    )}
                  </div>
                  <div className="flex gap-2 ml-4">
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => setSelectedMail(mail)}
                    >
                      <Eye className="w-4 h-4" />
                    </Button>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => handleDelete(mail.id)}
                      className="text-red-500 hover:text-red-600 hover:bg-red-50"
                    >
                      <Trash2 className="w-4 h-4" />
                    </Button>
                  </div>
                </div>
              ))}
            </div>
          )}

          {/* 페이징 */}
          {totalPages > 1 && (
            <div className="flex justify-center gap-2 mt-6">
              <Button
                variant="outline"
                size="sm"
                onClick={() => setPage((p) => Math.max(1, p - 1))}
                disabled={page === 1}
              >
                이전
              </Button>
              <div className="flex items-center px-4 text-sm text-gray-600">
                {page} / {totalPages}
              </div>
              <Button
                variant="outline"
                size="sm"
                onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
                disabled={page === totalPages}
              >
                다음
              </Button>
            </div>
          )}
        </CardContent>
      </Card>

      {/* 상세보기 모달 */}
      <Dialog open={selectedMail !== null} onOpenChange={(open) => !open && setSelectedMail(null)}>
        <DialogContent className="max-w-4xl max-h-[80vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                {selectedMail?.status === 'success' ? (
                  <CheckCircle2 className="w-5 h-5 text-green-500" />
                ) : (
                  <XCircle className="w-5 h-5 text-red-500" />
                )}
                <span>발송 상세 정보</span>
              </div>
              <Button
                variant="ghost"
                size="sm"
                onClick={() => setSelectedMail(null)}
              >
                <X className="w-4 h-4" />
              </Button>
            </DialogTitle>
          </DialogHeader>

          {selectedMail && (
            <div className="space-y-4">
              {/* 발송 정보 */}
              <Card>
                <CardHeader>
                  <CardTitle className="text-lg">발송 정보</CardTitle>
                </CardHeader>
                <CardContent className="space-y-3">
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <Label className="text-sm font-medium text-gray-700">발송 계정</Label>
                      <p className="text-sm text-gray-900 mt-1">
                        {selectedMail.accountName} ({selectedMail.accountEmail})
                      </p>
                    </div>
                    <div>
                      <Label className="text-sm font-medium text-gray-700">발송 시간</Label>
                      <p className="text-sm text-gray-900 mt-1">
                        {formatDate(selectedMail.sentAt)}
                      </p>
                    </div>
                  </div>

                  <div>
                    <Label className="text-sm font-medium text-gray-700">상태</Label>
                    <div className="mt-1">
                      {selectedMail.status === 'success' ? (
                        <span className="px-2 py-1 text-xs rounded-full bg-green-100 text-green-700">
                          발송 성공
                        </span>
                      ) : (
                        <span className="px-2 py-1 text-xs rounded-full bg-red-100 text-red-700">
                          발송 실패
                        </span>
                      )}
                    </div>
                  </div>

                  {selectedMail.messageId && (
                    <div>
                      <Label className="text-sm font-medium text-gray-700">메시지 ID</Label>
                      <p className="text-sm text-gray-600 mt-1 font-mono">
                        {selectedMail.messageId}
                      </p>
                    </div>
                  )}

                  {selectedMail.errorMessage && (
                    <div>
                      <Label className="text-sm font-medium text-red-700">오류 메시지</Label>
                      <p className="text-sm text-red-600 mt-1">
                        {selectedMail.errorMessage}
                      </p>
                    </div>
                  )}
                </CardContent>
              </Card>

              {/* 수신자 정보 */}
              <Card>
                <CardHeader>
                  <CardTitle className="text-lg">수신자 정보</CardTitle>
                </CardHeader>
                <CardContent className="space-y-3">
                  <div>
                    <Label className="text-sm font-medium text-gray-700">받는 사람</Label>
                    <div className="flex flex-wrap gap-2 mt-1">
                      {selectedMail.to.map((email, i) => (
                        <span key={i} className="px-2 py-1 text-xs rounded bg-blue-100 text-blue-700">
                          {email}
                        </span>
                      ))}
                    </div>
                  </div>

                  {selectedMail.cc && selectedMail.cc.length > 0 && (
                    <div>
                      <Label className="text-sm font-medium text-gray-700">참조 (CC)</Label>
                      <div className="flex flex-wrap gap-2 mt-1">
                        {selectedMail.cc.map((email, i) => (
                          <span key={i} className="px-2 py-1 text-xs rounded bg-green-100 text-green-700">
                            {email}
                          </span>
                        ))}
                      </div>
                    </div>
                  )}

                  {selectedMail.bcc && selectedMail.bcc.length > 0 && (
                    <div>
                      <Label className="text-sm font-medium text-gray-700">숨은참조 (BCC)</Label>
                      <div className="flex flex-wrap gap-2 mt-1">
                        {selectedMail.bcc.map((email, i) => (
                          <span key={i} className="px-2 py-1 text-xs rounded bg-purple-100 text-purple-700">
                            {email}
                          </span>
                        ))}
                      </div>
                    </div>
                  )}

                  {selectedMail.accepted && selectedMail.accepted.length > 0 && (
                    <div>
                      <Label className="text-sm font-medium text-green-700">수락됨</Label>
                      <p className="text-sm text-gray-600 mt-1">
                        {selectedMail.accepted.join(", ")}
                      </p>
                    </div>
                  )}

                  {selectedMail.rejected && selectedMail.rejected.length > 0 && (
                    <div>
                      <Label className="text-sm font-medium text-red-700">거부됨</Label>
                      <p className="text-sm text-gray-600 mt-1">
                        {selectedMail.rejected.join(", ")}
                      </p>
                    </div>
                  )}
                </CardContent>
              </Card>

              {/* 메일 내용 */}
              <Card>
                <CardHeader>
                  <CardTitle className="text-lg">메일 내용</CardTitle>
                </CardHeader>
                <CardContent className="space-y-3">
                  <div>
                    <Label className="text-sm font-medium text-gray-700">제목</Label>
                    <p className="text-sm text-gray-900 mt-1 font-medium">
                      {selectedMail.subject}
                    </p>
                  </div>

                  {selectedMail.templateName && (
                    <div>
                      <Label className="text-sm font-medium text-gray-700">사용한 템플릿</Label>
                      <p className="text-sm text-gray-600 mt-1">
                        {selectedMail.templateName}
                      </p>
                    </div>
                  )}

                  <div>
                    <Label className="text-sm font-medium text-gray-700">내용 미리보기</Label>
                    <div
                      className="mt-2 border rounded-lg p-4 bg-white max-h-96 overflow-y-auto"
                      dangerouslySetInnerHTML={{ __html: selectedMail.htmlContent }}
                    />
                  </div>
                </CardContent>
              </Card>

              {/* 첨부파일 */}
              {selectedMail.attachments && selectedMail.attachments.length > 0 && (
                <Card>
                  <CardHeader>
                    <CardTitle className="text-lg flex items-center gap-2">
                      <Paperclip className="w-5 h-5" />
                      첨부파일 ({selectedMail.attachments.length})
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="space-y-2">
                      {selectedMail.attachments.map((file, i) => (
                        <div
                          key={i}
                          className="flex items-center justify-between p-3 bg-gray-50 rounded-lg border"
                        >
                          <div className="flex items-center gap-3 flex-1 min-w-0">
                            <File className="w-5 h-5 text-gray-500 flex-shrink-0" />
                            <div className="flex-1 min-w-0">
                              <p className="text-sm font-medium text-gray-900 truncate">
                                {file.originalName}
                              </p>
                              <p className="text-xs text-gray-500">
                                {formatFileSize(file.size)} • {file.mimetype}
                              </p>
                            </div>
                          </div>
                        </div>
                      ))}
                    </div>
                  </CardContent>
                </Card>
              )}
            </div>
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
}

