"use client";

import { useState, useEffect } from "react";
import { getSentMailList, restoreMail, permanentlyDeleteMail, type SentMailHistory } from "@/lib/api/mail";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { RotateCcw, Trash2, Loader2, Mail, AlertCircle } from "lucide-react";
import { format } from "date-fns";
import { ko } from "date-fns/locale";

export default function TrashPage() {
  const [trashedMails, setTrashedMails] = useState<SentMailHistory[]>([]);
  const [loading, setLoading] = useState(true);
  const [restoring, setRestoring] = useState<string | null>(null);
  const [deleting, setDeleting] = useState<string | null>(null);

  useEffect(() => {
    loadTrashedMails();
  }, []);

  const loadTrashedMails = async () => {
    try {
      setLoading(true);
      const response = await getSentMailList({
        onlyDeleted: true,
        sortBy: "sentAt",
        sortOrder: "desc",
      });
      setTrashedMails(response.items);
    } catch (error) {
      // console.error("휴지통 메일 로드 실패:", error);
    } finally {
      setLoading(false);
    }
  };

  const handleRestore = async (id: string) => {
    try {
      setRestoring(id);
      await restoreMail(id);
      setTrashedMails(trashedMails.filter((m) => m.id !== id));
    } catch (error) {
      // console.error("메일 복구 실패:", error);
      alert("복구에 실패했습니다.");
    } finally {
      setRestoring(null);
    }
  };

  const handlePermanentDelete = async (id: string) => {
    if (!confirm("이 메일을 영구적으로 삭제하시겠습니까?\n이 작업은 되돌릴 수 없습니다.")) return;

    try {
      setDeleting(id);
      await permanentlyDeleteMail(id);
      setTrashedMails(trashedMails.filter((m) => m.id !== id));
    } catch (error) {
      // console.error("메일 영구 삭제 실패:", error);
      alert("삭제에 실패했습니다.");
    } finally {
      setDeleting(null);
    }
  };

  const handleEmptyTrash = async () => {
    if (!confirm(`휴지통의 모든 메일(${trashedMails.length}개)을 영구적으로 삭제하시겠습니까?\n이 작업은 되돌릴 수 없습니다.`)) return;

    try {
      setLoading(true);
      await Promise.all(trashedMails.map((mail) => permanentlyDeleteMail(mail.id)));
      setTrashedMails([]);
      alert("휴지통을 비웠습니다.");
    } catch (error) {
      // console.error("휴지통 비우기 실패:", error);
      alert("일부 메일 삭제에 실패했습니다.");
    } finally {
      setLoading(false);
    }
  };

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

  return (
    <div className="p-3 space-y-3">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-foreground">휴지통</h1>
          <p className="mt-2 text-muted-foreground">삭제된 메일은 30일 후 자동으로 영구 삭제됩니다</p>
        </div>
        {trashedMails.length > 0 && (
          <Button variant="destructive" onClick={handleEmptyTrash} className="h-10">
            <Trash2 className="w-4 h-4 mr-2" />
            휴지통 비우기
          </Button>
        )}
      </div>

      {trashedMails.length === 0 ? (
        <Card>
          <CardContent className="flex flex-col items-center justify-center py-12">
            <Mail className="w-12 h-12 text-muted-foreground mb-4" />
            <p className="text-muted-foreground">휴지통이 비어 있습니다</p>
          </CardContent>
        </Card>
      ) : (
        <div className="grid gap-3">
          {trashedMails.map((mail) => {
            const deletedDate = mail.deletedAt ? new Date(mail.deletedAt) : null;
            const daysLeft = deletedDate
              ? Math.max(0, 30 - Math.floor((Date.now() - deletedDate.getTime()) / (1000 * 60 * 60 * 24)))
              : 30;

            return (
              <Card key={mail.id} className="hover:shadow-md transition-shadow">
                <CardHeader className="pb-3">
                  <div className="flex items-start justify-between">
                    <div className="flex-1 min-w-0">
                      <CardTitle className="text-lg truncate">
                        {mail.subject || "(제목 없음)"}
                      </CardTitle>
                      <CardDescription className="mt-1">
                        받는 사람: {mail.to.join(", ") || "(없음)"}
                      </CardDescription>
                    </div>
                    <div className="flex items-center gap-2 ml-4">
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => handleRestore(mail.id)}
                        disabled={restoring === mail.id}
                        className="h-8"
                      >
                        {restoring === mail.id ? (
                          <Loader2 className="w-4 h-4 animate-spin" />
                        ) : (
                          <>
                            <RotateCcw className="w-4 h-4 mr-1" />
                            복구
                          </>
                        )}
                      </Button>
                      <Button
                        variant="destructive"
                        size="sm"
                        onClick={() => handlePermanentDelete(mail.id)}
                        disabled={deleting === mail.id}
                        className="h-8"
                      >
                        {deleting === mail.id ? (
                          <Loader2 className="w-4 h-4 animate-spin" />
                        ) : (
                          <>
                            <Trash2 className="w-4 h-4 mr-1" />
                            영구 삭제
                          </>
                        )}
                      </Button>
                    </div>
                  </div>
                </CardHeader>
                <CardContent className="pt-0">
                  <div className="flex items-center justify-between text-sm">
                    <span className="text-muted-foreground">
                      계정: {mail.accountName || mail.accountEmail}
                    </span>
                    <span className="text-muted-foreground">
                      {format(new Date(mail.sentAt), "yyyy-MM-dd HH:mm", { locale: ko })}
                    </span>
                  </div>
                  {daysLeft <= 7 && (
                    <div className="flex items-center gap-2 mt-2 text-xs text-amber-600">
                      <AlertCircle className="w-3 h-3" />
                      <span>{daysLeft}일 후 자동 삭제됩니다</span>
                    </div>
                  )}
                </CardContent>
              </Card>
            );
          })}
        </div>
      )}
    </div>
  );
}


