"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 { Badge } from "@/components/ui/badge";
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,
  ChevronRight,
  ChevronDown,
  ChevronUp,
  Send,
  AlertCircle,
} from "lucide-react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { Separator } from "@/components/ui/separator";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  SentMailHistory,
  getSentMailList,
  deleteSentMail,
  getMailAccounts,
  MailAccount,
  getMailStatistics,
} 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 [showFilters, setShowFilters] = useState(false);

  // 통계
  const [stats, setStats] = useState({
    totalSent: 0,
    successCount: 0,
    failedCount: 0,
    todayCount: 0,
  });

  // 필터 및 페이징
  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();
    loadStats();
  }, []);

  useEffect(() => {
    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 loadStats = async () => {
    try {
      const data = await getMailStatistics();
      setStats({
        totalSent: data.totalSent,
        successCount: data.successCount,
        failedCount: data.failedCount,
        todayCount: data.todayCount,
      });
    } catch (error: unknown) {
      console.error('통계 로드 실패:', error);
    }
  };

  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();
      loadStats();
    } 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 && mails.length === 0) {
    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-background min-h-screen">
      {/* 헤더 */}
      <div className="bg-card rounded-lg border p-6 space-y-4">
        {/* 브레드크럼브 */}
        <nav className="flex items-center gap-2 text-sm">
          <Link 
            href="/admin/mail/dashboard"
            className="text-muted-foreground hover:text-foreground transition-colors"
          >
            메일 관리
          </Link>
          <ChevronRight className="w-4 h-4 text-muted-foreground" />
          <span className="text-foreground font-medium">발송 내역</span>
        </nav>
        
        <Separator />
        
        {/* 제목 및 빠른 액션 */}
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-3xl font-bold text-foreground flex items-center gap-2">
              <Inbox className="w-8 h-8" />
              보낸메일함
            </h1>
            <p className="mt-2 text-muted-foreground">총 {total}개의 발송 이력</p>
          </div>
          <Button onClick={loadMails} variant="outline" size="sm">
            <RefreshCw className="w-4 h-4 mr-2" />
            새로고침
          </Button>
        </div>
      </div>

      {/* 통계 카드 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card>
          <CardContent className="pt-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-muted-foreground">전체 발송</p>
                <p className="text-2xl font-bold text-foreground mt-1">{stats.totalSent}</p>
              </div>
              <div className="p-3 bg-muted rounded-lg">
                <Send className="w-6 h-6 text-muted-foreground" />
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="pt-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-muted-foreground">발송 성공</p>
                <p className="text-2xl font-bold text-foreground mt-1">{stats.successCount}</p>
              </div>
              <div className="p-3 bg-muted rounded-lg">
                <CheckCircle2 className="w-6 h-6 text-muted-foreground" />
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="pt-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-muted-foreground">발송 실패</p>
                <p className="text-2xl font-bold text-foreground mt-1">{stats.failedCount}</p>
              </div>
              <div className="p-3 bg-muted rounded-lg">
                <XCircle className="w-6 h-6 text-muted-foreground" />
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="pt-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-muted-foreground">오늘 발송</p>
                <p className="text-2xl font-bold text-foreground mt-1">{stats.todayCount}</p>
              </div>
              <div className="p-3 bg-muted rounded-lg">
                <Calendar className="w-6 h-6 text-muted-foreground" />
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* 검색 및 필터 */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <Search className="w-5 h-5" />
              <CardTitle>검색</CardTitle>
            </div>
            <Button
              variant="ghost"
              size="sm"
              onClick={() => setShowFilters(!showFilters)}
            >
              <Filter className="w-4 h-4 mr-2" />
              고급 필터
              {showFilters ? <ChevronUp className="w-4 h-4 ml-1" /> : <ChevronDown className="w-4 h-4 ml-1" />}
            </Button>
          </div>
        </CardHeader>
        <CardContent className="space-y-4">
          {/* 기본 검색 */}
          <div className="flex gap-2">
            <Input
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
              placeholder="제목 또는 받는사람으로 검색..."
              className="flex-1"
            />
            <Button onClick={handleSearch}>
              <Search className="w-4 h-4 mr-2" />
              검색
            </Button>
          </div>

          {/* 고급 필터 (접기/펼치기) */}
          {showFilters && (
            <div className="pt-4 border-t space-y-4">
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                {/* 상태 필터 */}
                <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((acc) => (
                        <SelectItem key={acc.id} value={acc.id}>
                          {acc.name}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>

                {/* 정렬 */}
                <div>
                  <Label>정렬</Label>
                  <Select value={`${sortBy}-${sortOrder}`} onValueChange={(v) => {
                    const [by, order] = v.split('-');
                    setSortBy(by as 'sentAt' | 'subject');
                    setSortOrder(order as 'asc' | 'desc');
                    setPage(1);
                  }}>
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="sentAt-desc">최신순</SelectItem>
                      <SelectItem value="sentAt-asc">오래된순</SelectItem>
                      <SelectItem value="subject-asc">제목 (가나다순)</SelectItem>
                      <SelectItem value="subject-desc">제목 (역순)</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>

              {/* 필터 초기화 */}
              <Button
                variant="outline"
                size="sm"
                onClick={() => {
                  setSearchTerm("");
                  setFilterStatus('all');
                  setFilterAccountId('all');
                  setSortBy('sentAt');
                  setSortOrder('desc');
                  setPage(1);
                }}
              >
                <X className="w-4 h-4 mr-2" />
                필터 초기화
              </Button>
            </div>
          )}
        </CardContent>
      </Card>

      {/* 메일 목록 */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Mail className="w-5 h-5" />
            발송 이력 ({total}건)
          </CardTitle>
        </CardHeader>
        <CardContent>
          {loading ? (
            <div className="flex items-center justify-center py-12">
              <Loader2 className="w-6 h-6 animate-spin text-primary" />
            </div>
          ) : mails.length === 0 ? (
            <div className="text-center py-12">
              <Inbox className="w-16 h-16 mx-auto text-muted-foreground mb-4" />
              <p className="text-muted-foreground">발송 이력이 없습니다</p>
            </div>
          ) : (
            <div className="space-y-3">
              {mails.map((mail) => (
                <div
                  key={mail.id}
                  className="p-4 border rounded-lg hover:bg-muted/50 transition-colors"
                >
                  <div className="flex items-start justify-between gap-4">
                    {/* 메일 정보 */}
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2 mb-2">
                        {/* 상태 배지 */}
                        {mail.status === 'success' ? (
                          <Badge variant="default" className="bg-green-100 text-green-700 hover:bg-green-100">
                            <CheckCircle2 className="w-3 h-3 mr-1" />
                            발송 성공
                          </Badge>
                        ) : (
                          <Badge variant="destructive">
                            <XCircle className="w-3 h-3 mr-1" />
                            발송 실패
                          </Badge>
                        )}
                        
                        {/* 첨부파일 */}
                        {mail.attachmentCount > 0 && (
                          <Badge variant="outline">
                            <Paperclip className="w-3 h-3 mr-1" />
                            {mail.attachmentCount}개
                          </Badge>
                        )}
                      </div>

                      {/* 제목 */}
                      <h3 className="font-semibold text-foreground mb-1 truncate">
                        {mail.subject || "(제목 없음)"}
                      </h3>

                      {/* 수신자 및 날짜 */}
                      <div className="flex flex-wrap items-center gap-3 text-sm text-muted-foreground">
                        <span className="flex items-center gap-1">
                          <User className="w-3 h-3" />
                          {Array.isArray(mail.to) ? mail.to.join(", ") : mail.to}
                        </span>
                        <span className="flex items-center gap-1">
                          <Calendar className="w-3 h-3" />
                          {formatDate(mail.sentAt)}
                        </span>
                      </div>

                      {/* 실패 메시지 */}
                      {mail.status === 'failed' && mail.errorMessage && (
                        <div className="mt-2 text-sm text-red-600 flex items-center gap-1">
                          <AlertCircle className="w-3 h-3" />
                          {mail.errorMessage}
                        </div>
                      )}
                    </div>

                    {/* 액션 버튼 */}
                    <div className="flex items-center gap-2">
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => setSelectedMail(mail)}
                      >
                        <Eye className="w-4 h-4" />
                      </Button>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => handleDelete(mail.id)}
                      >
                        <Trash2 className="w-4 h-4" />
                      </Button>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}

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

      {/* 메일 상세 모달 */}
      {selectedMail && (
        <Dialog open={!!selectedMail} onOpenChange={() => setSelectedMail(null)}>
          <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
            <DialogHeader>
              <DialogTitle className="flex items-center gap-2">
                <Mail className="w-5 h-5" />
                발송 상세정보
              </DialogTitle>
            </DialogHeader>

            <div className="space-y-6">
              {/* 상태 */}
              <div>
                {selectedMail.status === 'success' ? (
                  <Badge variant="default" className="bg-green-100 text-green-700 hover:bg-green-100">
                    <CheckCircle2 className="w-4 h-4 mr-1" />
                    발송 성공
                  </Badge>
                ) : (
                  <Badge variant="destructive">
                    <XCircle className="w-4 h-4 mr-1" />
                    발송 실패
                  </Badge>
                )}
                {selectedMail.status === 'failed' && selectedMail.errorMessage && (
                  <p className="mt-2 text-sm text-red-600">{selectedMail.errorMessage}</p>
                )}
              </div>

              <Separator />

              {/* 발신 정보 */}
              <div className="space-y-4">
                <h3 className="font-semibold text-foreground">발신 정보</h3>
                <div className="space-y-2 text-sm">
                  <div className="flex">
                    <span className="w-24 text-muted-foreground">보낸사람:</span>
                    <span className="flex-1 font-medium">{selectedMail.from}</span>
                  </div>
                  <div className="flex">
                    <span className="w-24 text-muted-foreground">받는사람:</span>
                    <span className="flex-1">
                      {Array.isArray(selectedMail.to) ? selectedMail.to.join(", ") : selectedMail.to}
                    </span>
                  </div>
                  {selectedMail.cc && selectedMail.cc.length > 0 && (
                    <div className="flex">
                      <span className="w-24 text-muted-foreground">참조:</span>
                      <span className="flex-1">{selectedMail.cc.join(", ")}</span>
                    </div>
                  )}
                  {selectedMail.bcc && selectedMail.bcc.length > 0 && (
                    <div className="flex">
                      <span className="w-24 text-muted-foreground">숨은참조:</span>
                      <span className="flex-1">{selectedMail.bcc.join(", ")}</span>
                    </div>
                  )}
                  <div className="flex">
                    <span className="w-24 text-muted-foreground">발송일시:</span>
                    <span className="flex-1">{formatDate(selectedMail.sentAt)}</span>
                  </div>
                </div>
              </div>

              <Separator />

              {/* 메일 내용 */}
              <div className="space-y-4">
                <h3 className="font-semibold text-foreground">메일 내용</h3>
                <div>
                  <p className="text-sm text-muted-foreground mb-2">제목</p>
                  <p className="font-medium">{selectedMail.subject || "(제목 없음)"}</p>
                </div>
                {selectedMail.templateUsed && (
                  <div>
                    <p className="text-sm text-muted-foreground mb-2">사용 템플릿</p>
                    <Badge variant="outline">{selectedMail.templateUsed}</Badge>
                  </div>
                )}
                <div>
                  <p className="text-sm text-muted-foreground mb-2">본문</p>
                  <div 
                    className="p-4 border rounded-lg bg-muted/30 max-h-96 overflow-y-auto"
                    dangerouslySetInnerHTML={{ __html: selectedMail.htmlBody || selectedMail.textBody || "" }}
                  />
                </div>
              </div>

              {/* 첨부파일 */}
              {selectedMail.attachments && selectedMail.attachments.length > 0 && (
                <>
                  <Separator />
                  <div className="space-y-4">
                    <h3 className="font-semibold text-foreground flex items-center gap-2">
                      <Paperclip className="w-4 h-4" />
                      첨부파일 ({selectedMail.attachments.length}개)
                    </h3>
                    <div className="space-y-2">
                      {selectedMail.attachments.map((att, idx) => (
                        <div key={idx} className="flex items-center justify-between p-3 border rounded-lg">
                          <div className="flex items-center gap-3">
                            <File className="w-5 h-5 text-muted-foreground" />
                            <div>
                              <p className="text-sm font-medium">{att.filename}</p>
                              <p className="text-xs text-muted-foreground">{formatFileSize(att.size || 0)}</p>
                            </div>
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                </>
              )}

              {/* 수신 결과 (성공/실패 목록) */}
              {selectedMail.acceptedRecipients && selectedMail.acceptedRecipients.length > 0 && (
                <>
                  <Separator />
                  <div className="space-y-2">
                    <h3 className="font-semibold text-foreground text-sm">수신 성공</h3>
                    <div className="flex flex-wrap gap-2">
                      {selectedMail.acceptedRecipients.map((email, idx) => (
                        <Badge key={idx} variant="default" className="bg-green-100 text-green-700 hover:bg-green-100">
                          {email}
                        </Badge>
                      ))}
                    </div>
                  </div>
                </>
              )}
              {selectedMail.rejectedRecipients && selectedMail.rejectedRecipients.length > 0 && (
                <>
                  <Separator />
                  <div className="space-y-2">
                    <h3 className="font-semibold text-foreground text-sm">수신 실패</h3>
                    <div className="flex flex-wrap gap-2">
                      {selectedMail.rejectedRecipients.map((email, idx) => (
                        <Badge key={idx} variant="destructive">
                          {email}
                        </Badge>
                      ))}
                    </div>
                  </div>
                </>
              )}
            </div>
          </DialogContent>
        </Dialog>
      )}
    </div>
  );
}
