"use client";

import React, { useState } from "react";
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import {
  Mail,
  Search,
  Send,
  Archive,
  Star,
  Trash2,
  Reply,
  Forward,
  MoreVertical,
  Paperclip,
  Clock,
} from "lucide-react";
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">
            <Send className="mr-2 h-4 w-4" />
            Nouveau message
          </Button>
        </Link>
      </div>

      {/* Navigation */}
      <div className="flex gap-2">
        <Link href="/messages">
          <Button variant="default" className="bg-blue-600">
            <Mail className="mr-2 h-4 w-4" />
            Reçus
          </Button>
        </Link>
        <Link href="/messages/envoyes">
          <Button variant="outline">
            <Send className="mr-2 h-4 w-4" />
            Envoyés
          </Button>
        </Link>
        <Link href="/messages/archives">
          <Button variant="outline">
            <Archive className="mr-2 h-4 w-4" />
            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]">
            <div className="relative">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
              <Input
                placeholder="Rechercher dans les messages..."
                className="pl-10"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
              />
            </div>
          </div>
          <div className="flex gap-2">
            <Button
              variant={filterStatus === "all" ? "default" : "outline"}
              onClick={() => setFilterStatus("all")}
            >
              Tous
            </Button>
            <Button
              variant={filterStatus === "unread" ? "default" : "outline"}
              onClick={() => setFilterStatus("unread")}
            >
              Non lus ({unreadCount})
            </Button>
            <Button
              variant={filterStatus === "starred" ? "default" : "outline"}
              onClick={() => setFilterStatus("starred")}
            >
              <Star className="mr-1 h-4 w-4" />
              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
              variant="outline"
              size="sm"
              onClick={() => setSelectedMessages([])}
            >
              Tout désélectionner
            </Button>
            <div className="flex-1" />
            <Button variant="outline" size="sm">
              <Archive className="mr-2 h-4 w-4" />
              Archiver
            </Button>
            <Button variant="outline" size="sm">
              <Trash2 className="mr-2 h-4 w-4" />
              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();
                    }}
                  >
                    <Star
                      className={`h-5 w-5 ${
                        message.isStarred
                          ? "fill-yellow-400 text-yellow-400"
                          : "text-gray-400"
                      }`}
                    />
                  </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 && (
                            <Paperclip className="h-4 w-4 text-gray-400" />
                          )}
                        </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"
                        >
                          <MoreVertical className="h-4 w-4 text-gray-400" />
                        </button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            ))
          ) : (
            <div className="p-12 text-center">
              <Mail className="h-12 w-12 text-gray-400 mx-auto mb-4" />
              <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">
              <Mail className="h-6 w-6 text-blue-600" />
            </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">
              <Clock className="h-6 w-6 text-orange-600" />
            </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">
              <Star className="h-6 w-6 text-yellow-600" />
            </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">
              <Send className="h-6 w-6 text-green-600" />
            </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>
  );
}
