"use client";

import { useEffect, useState } from "react";
import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation";
import { MailToolbar } from "@/components/mail/mail-toolbar";
import { MailList } from "@/components/mail/mail-list";
import { useMail } from "@/hooks/use-mail";
import { Mail } from "@/types/mail";

export default function CourrierPage() {
  const { data: session } = useSession();
  const router = useRouter();
  const { mails, loading, error, fetchMails } = useMail();
  const [searchQuery, setSearchQuery] = useState("");

  useEffect(() => {
    if (!session) {
      router.push("/signin");
      return;
    }

    // Check if we have mail credentials
    const mailCredentials = localStorage.getItem("mailCredentials");
    if (mailCredentials) {
      fetchMails();
    }
  }, [session, router, fetchMails]);

  const handleRefresh = () => {
    fetchMails();
  };

  const handleCompose = () => {
    // TODO: Implement compose functionality
  };

  const handleSearch = (query: string) => {
    setSearchQuery(query);
  };

  const handleMailClick = (mail: Mail) => {
    // TODO: Implement mail view functionality
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-screen">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-gray-900"></div>
          <p className="mt-4 text-gray-600">Chargement des courriers...</p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center h-screen">
        <div className="text-center">
          <p className="text-red-600">Erreur: {error}</p>
          <button
            onClick={handleRefresh}
            className="mt-4 px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"
          >
            Réessayer
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="flex flex-col h-screen">
      <MailToolbar
        onRefresh={handleRefresh}
        onCompose={handleCompose}
        onSearch={handleSearch}
      />
      <div className="flex-1 overflow-auto">
        <MailList
          mails={mails}
          onMailClick={handleMailClick}
        />
      </div>
    </div>
  );
} 