import { createFileRoute } from "@tanstack/react-router";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { supabase } from "@/integrations/supabase/client";
import { Mail, Phone, Trash2, Inbox } from "lucide-react";
import { toast } from "sonner";
import { useState } from "react";

export const Route = createFileRoute("/admin/messages")({
  component: AdminMessages,
});

type Message = {
  id: string;
  name: string;
  email: string;
  phone: string;
  message: string;
  status: string;
  admin_notes: string | null;
  created_at: string;
};

const STATUSES = [
  { value: "new", label: "Nouveau" },
  { value: "in_progress", label: "En cours" },
  { value: "done", label: "Traité" },
  { value: "archived", label: "Archivé" },
];

function AdminMessages() {
  const qc = useQueryClient();
  const [filter, setFilter] = useState<string>("all");

  const { data: messages = [], isLoading } = useQuery({
    queryKey: ["contact_messages"],
    queryFn: async () => {
      const { data, error } = await supabase
        .from("contact_messages")
        .select("*")
        .order("created_at", { ascending: false });
      if (error) throw error;
      return data as Message[];
    },
  });

  const updateStatus = useMutation({
    mutationFn: async ({ id, status }: { id: string; status: string }) => {
      const { error } = await supabase.from("contact_messages").update({ status }).eq("id", id);
      if (error) throw error;
    },
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["contact_messages"] });
      toast.success("Statut mis à jour");
    },
  });

  const remove = useMutation({
    mutationFn: async (id: string) => {
      const { error } = await supabase.from("contact_messages").delete().eq("id", id);
      if (error) throw error;
    },
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["contact_messages"] });
      toast.success("Message supprimé");
    },
  });

  const filtered = filter === "all" ? messages : messages.filter((m) => m.status === filter);
  const newCount = messages.filter((m) => m.status === "new").length;

  return (
    <div className="p-8 max-w-6xl">
      <div className="flex items-center justify-between mb-8">
        <div>
          <h1 className="font-display text-3xl font-bold flex items-center gap-3">
            <Inbox className="size-7 text-primary" /> Messages
          </h1>
          <p className="text-sm text-muted-foreground mt-1">
            {messages.length} message{messages.length > 1 ? "s" : ""} · {newCount} nouveau{newCount > 1 ? "x" : ""}
          </p>
        </div>
      </div>

      <div className="flex gap-2 mb-6 flex-wrap">
        <FilterChip active={filter === "all"} onClick={() => setFilter("all")} label={`Tous (${messages.length})`} />
        {STATUSES.map((s) => {
          const count = messages.filter((m) => m.status === s.value).length;
          return (
            <FilterChip
              key={s.value}
              active={filter === s.value}
              onClick={() => setFilter(s.value)}
              label={`${s.label} (${count})`}
            />
          );
        })}
      </div>

      {isLoading ? (
        <div className="text-muted-foreground">Chargement…</div>
      ) : filtered.length === 0 ? (
        <div className="rounded-2xl border border-border bg-card/40 p-12 text-center text-muted-foreground">
          Aucun message {filter !== "all" ? "dans cette catégorie" : "pour le moment"}.
        </div>
      ) : (
        <div className="space-y-4">
          {filtered.map((m) => (
            <article key={m.id} className="rounded-2xl border border-border bg-card/40 p-6 backdrop-blur">
              <div className="flex items-start justify-between gap-4 flex-wrap">
                <div>
                  <h3 className="font-semibold text-lg">{m.name}</h3>
                  <div className="mt-2 flex flex-wrap gap-4 text-sm text-muted-foreground">
                    <a href={`mailto:${m.email}`} className="flex items-center gap-1.5 hover:text-primary">
                      <Mail className="size-3.5" /> {m.email}
                    </a>
                    <a href={`tel:${m.phone}`} className="flex items-center gap-1.5 hover:text-primary">
                      <Phone className="size-3.5" /> {m.phone}
                    </a>
                    <span className="text-xs">{new Date(m.created_at).toLocaleString("fr-FR")}</span>
                  </div>
                </div>
                <div className="flex items-center gap-2">
                  <select
                    value={m.status}
                    onChange={(e) => updateStatus.mutate({ id: m.id, status: e.target.value })}
                    className="rounded-lg bg-input/60 border border-border px-3 py-1.5 text-xs focus:outline-none focus:border-primary"
                  >
                    {STATUSES.map((s) => (
                      <option key={s.value} value={s.value}>{s.label}</option>
                    ))}
                  </select>
                  <button
                    onClick={() => { if (confirm("Supprimer ce message ?")) remove.mutate(m.id); }}
                    className="p-2 rounded-lg text-muted-foreground hover:bg-destructive/10 hover:text-destructive"
                    aria-label="Supprimer"
                  >
                    <Trash2 className="size-4" />
                  </button>
                </div>
              </div>
              <p className="mt-4 text-sm whitespace-pre-wrap rounded-lg bg-background/40 border border-border p-4">
                {m.message}
              </p>
            </article>
          ))}
        </div>
      )}
    </div>
  );
}

function FilterChip({ active, onClick, label }: { active: boolean; onClick: () => void; label: string }) {
  return (
    <button
      onClick={onClick}
      className={`px-4 py-1.5 rounded-full text-xs font-medium transition-colors ${
        active ? "bg-primary text-primary-foreground" : "bg-secondary text-muted-foreground hover:text-foreground"
      }`}
    >
      {label}
    </button>
  );
}
