"use client";

import React, { useState } from "react";
import { Card } from "primereact/card";
import { Button } from "primereact/button";
import { InputText } from "primereact/inputtext";
import Link from "next/link";

/**
 * Page principale de la messagerie - Boîte de réception
 * Affiche tous les messages reçus avec filtrage et recherche
 */
export default function MessagesPage() {
  const [selectedMessages, setSelectedMessages] = useState<string[]>([]);
  const [searchTerm, setSearchTerm] = useState("");
  const [filterStatus, setFilterStatus] = useState<"all" | "unread" | "starred">(
    "all"
  );

  // Messages mockés pour démonstration
  const messages = [
    {
      id: "1",
      from: "Jean Dupont",
      fromEmail: "jean.dupont@btpxpress.fr",
      subject: "Demande de devis pour chantier Lyon",
      preview:
        "Bonjour, je souhaiterais obtenir un devis pour la construction d'un immeuble...",
      date: "2025-10-30T10:30:00",
      isRead: false,
      isStarred: true,
      hasAttachment: true,
    },
    {
      id: "2",
      from: "Marie Martin",
      fromEmail: "marie.martin@client.fr",
      subject: "Validation planning chantier",
      preview: "Le planning que vous avez envoyé me convient parfaitement...",
      date: "2025-10-30T09:15:00",
      isRead: true,
      isStarred: false,
      hasAttachment: false,
    },
    {
      id: "3",
      from: "Pierre Leblanc",
      fromEmail: "p.leblanc@entreprise.com",
      subject: "Question sur facture #2024-103",
      preview: "J'ai une question concernant la facture que j'ai reçue...",
      date: "2025-10-29T16:45:00",
      isRead: false,
      isStarred: false,
      hasAttachment: true,
    },
    {
      id: "4",
      from: "Sophie Bernard",
      fromEmail: "sophie.b@construction.fr",
      subject: "Proposition de collaboration",
      preview: "Nous sommes intéressés par une collaboration sur plusieurs projets...",
      date: "2025-10-29T14:20:00",
      isRead: true,
      isStarred: true,
      hasAttachment: false,
    },
  ];

  const filteredMessages = messages.filter((message) => {
    const matchesSearch =
      message.from.toLowerCase().includes(searchTerm.toLowerCase()) ||
      message.subject.toLowerCase().includes(searchTerm.toLowerCase());

    const matchesFilter =
      filterStatus === "all" ||
      (filterStatus === "unread" && !message.isRead) ||
      (filterStatus === "starred" && message.isStarred);

    return matchesSearch && matchesFilter;
  });

  const toggleSelectMessage = (id: string) => {
    setSelectedMessages((prev) =>
      prev.includes(id) ? prev.filter((msgId) => msgId !== id) : [...prev, id]
    );
  };

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    const now = new Date();
    const diffInHours = (now.getTime() - date.getTime()) / (1000 * 60 * 60);

    if (diffInHours < 24) {
      return date.toLocaleTimeString("fr-FR", {
        hour: "2-digit",
        minute: "2-digit",
      });
    } else if (diffInHours < 48) {
      return "Hier";
    } else {
      return date.toLocaleDateString("fr-FR", {
        day: "2-digit",
        month: "short",
      });
    }
  };

  const unreadCount = messages.filter((m) => !m.isRead).length;

  return (
    <div className="space-y-6 p-6">
      {/* En-tête */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-gray-900">Messagerie</h1>
          <p className="text-gray-500 mt-1">
            {unreadCount} message{unreadCount > 1 ? "s" : ""} non lu
            {unreadCount > 1 ? "s" : ""}
          </p>
        </div>
        <Link href="/messages/nouveau">
          <Button className="bg-blue-600 hover:bg-blue-700">
            <i className="pi pi-send mr-2"></i>
            Nouveau message
          </Button>
        </Link>
      </div>

      {/* Navigation */}
      <div className="flex gap-2">
        <Link href="/messages">
          <Button className="bg-blue-600">
            <i className="pi pi-envelope mr-2"></i>
            Reçus
          </Button>
        </Link>
        <Link href="/messages/envoyes">
          <Button outlined>
            <i className="pi pi-send mr-2"></i>
            Envoyés
          </Button>
        </Link>
        <Link href="/messages/archives">
          <Button outlined>
            <i className="pi pi-inbox mr-2"></i>
            Archives
          </Button>
        </Link>
      </div>

      {/* Barre de recherche et filtres */}
      <Card className="p-4">
        <div className="flex gap-4 flex-wrap">
          <div className="flex-1 min-w-[300px]">
            <span className="p-input-icon-left w-full">
              <i className="pi pi-search" />
              <InputText
                placeholder="Rechercher dans les messages..."
                className="w-full"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
              />
            </span>
          </div>
          <div className="flex gap-2">
            <Button
              outlined={filterStatus !== "all"}
              onClick={() => setFilterStatus("all")}
            >
              Tous
            </Button>
            <Button
              outlined={filterStatus !== "unread"}
              onClick={() => setFilterStatus("unread")}
            >
              Non lus ({unreadCount})
            </Button>
            <Button
              outlined={filterStatus !== "starred"}
              onClick={() => setFilterStatus("starred")}
            >
              <i className="pi pi-star mr-1"></i>
              Favoris
            </Button>
          </div>
        </div>
      </Card>

      {/* Actions groupées */}
      {selectedMessages.length > 0 && (
        <Card className="p-4">
          <div className="flex items-center gap-4">
            <span className="text-sm text-gray-600">
              {selectedMessages.length} message{selectedMessages.length > 1 ? "s" : ""}{" "}
              sélectionné{selectedMessages.length > 1 ? "s" : ""}
            </span>
            <Button
              outlined
              size="small"
              onClick={() => setSelectedMessages([])}
            >
              Tout désélectionner
            </Button>
            <div className="flex-1" />
            <Button outlined size="small">
              <i className="pi pi-inbox mr-2"></i>
              Archiver
            </Button>
            <Button outlined size="small">
              <i className="pi pi-trash mr-2"></i>
              Supprimer
            </Button>
          </div>
        </Card>
      )}

      {/* Liste des messages */}
      <Card>
        <div className="divide-y">
          {filteredMessages.length > 0 ? (
            filteredMessages.map((message) => (
              <div
                key={message.id}
                className={`p-4 hover:bg-gray-50 transition-colors cursor-pointer ${
                  !message.isRead ? "bg-blue-50" : ""
                }`}
                onClick={() => toggleSelectMessage(message.id)}
              >
                <div className="flex items-start gap-4">
                  {/* Checkbox */}
                  <input
                    type="checkbox"
                    checked={selectedMessages.includes(message.id)}
                    onChange={() => toggleSelectMessage(message.id)}
                    className="mt-1"
                    onClick={(e) => e.stopPropagation()}
                  />

                  {/* Star */}
                  <button
                    className="mt-1"
                    onClick={(e) => {
                      e.stopPropagation();
                    }}
                  >
                    <i
                      className={`pi ${
                        message.isStarred
                          ? "pi-star-fill text-yellow-400"
                          : "pi-star text-gray-400"
                      }`}
                      style={{ fontSize: '1.25rem' }}
                    ></i>
                  </button>

                  {/* Contenu du message */}
                  <div className="flex-1 min-w-0">
                    <div className="flex items-start justify-between gap-4">
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-2">
                          <p
                            className={`font-semibold ${
                              !message.isRead ? "font-bold" : ""
                            }`}
                          >
                            {message.from}
                          </p>
                          {message.hasAttachment && (
                            <i className="pi pi-paperclip text-gray-400"></i>
                          )}
                        </div>
                        <p
                          className={`text-sm ${
                            !message.isRead
                              ? "font-semibold text-gray-900"
                              : "text-gray-600"
                          } truncate`}
                        >
                          {message.subject}
                        </p>
                        <p className="text-sm text-gray-500 truncate mt-1">
                          {message.preview}
                        </p>
                      </div>
                      <div className="flex items-center gap-4 flex-shrink-0">
                        <span className="text-sm text-gray-500">
                          {formatDate(message.date)}
                        </span>
                        <button
                          onClick={(e) => e.stopPropagation()}
                          className="hover:bg-gray-200 rounded p-1"
                        >
                          <i className="pi pi-ellipsis-v text-gray-400"></i>
                        </button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            ))
          ) : (
            <div className="p-12 text-center">
              <i className="pi pi-envelope text-gray-400 mx-auto mb-4" style={{ fontSize: '3rem' }}></i>
              <p className="text-gray-500">Aucun message trouvé</p>
            </div>
          )}
        </div>
      </Card>

      {/* Statistiques */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card className="p-4">
          <div className="flex items-center gap-4">
            <div className="p-3 bg-blue-100 rounded-lg">
              <i className="pi pi-envelope text-blue-600" style={{ fontSize: '1.5rem' }}></i>
            </div>
            <div>
              <p className="text-2xl font-bold">{messages.length}</p>
              <p className="text-sm text-gray-500">Messages reçus</p>
            </div>
          </div>
        </Card>
        <Card className="p-4">
          <div className="flex items-center gap-4">
            <div className="p-3 bg-orange-100 rounded-lg">
              <i className="pi pi-clock text-orange-600" style={{ fontSize: '1.5rem' }}></i>
            </div>
            <div>
              <p className="text-2xl font-bold">{unreadCount}</p>
              <p className="text-sm text-gray-500">Non lus</p>
            </div>
          </div>
        </Card>
        <Card className="p-4">
          <div className="flex items-center gap-4">
            <div className="p-3 bg-yellow-100 rounded-lg">
              <i className="pi pi-star text-yellow-600" style={{ fontSize: '1.5rem' }}></i>
            </div>
            <div>
              <p className="text-2xl font-bold">
                {messages.filter((m) => m.isStarred).length}
              </p>
              <p className="text-sm text-gray-500">Favoris</p>
            </div>
          </div>
        </Card>
        <Card className="p-4">
          <div className="flex items-center gap-4">
            <div className="p-3 bg-green-100 rounded-lg">
              <i className="pi pi-send text-green-600" style={{ fontSize: '1.5rem' }}></i>
            </div>
            <div>
              <p className="text-2xl font-bold">12</p>
              <p className="text-sm text-gray-500">Envoyés</p>
            </div>
          </div>
        </Card>
      </div>
    </div>
  );
}
