"use client";

import { useState, useTransition, useRef, useEffect } from "react";
import { useRouter } from "next/navigation";
import type { ClientView } from "@/lib/client-view";
import type { Comment } from "@/db/schema";

type Entity = { id: string; type: "general" | "task" | "deliverable"; label: string };

function buildEntityList(clientId: string, phases: ClientView["phases"]): Entity[] {
  const entities: Entity[] = [
    { id: clientId, type: "general", label: "Messaggio generale" },
  ];
  for (const phase of phases) {
    for (const task of phase.tasks) {
      entities.push({
        id: task.id,
        type: "task",
        label: `${phase.title} — ${task.title}`,
      });
      for (const d of task.deliverables) {
        entities.push({
          id: d.id,
          type: "deliverable",
          label: `${task.title} — ${d.title}`,
        });
      }
    }
  }
  return entities;
}

function buildLabelMap(entities: Entity[]): Map<string, string> {
  const map = new Map<string, string>();
  for (const e of entities) map.set(e.id, e.label);
  return map;
}

function formatTime(ts: Date | string): string {
  const d = typeof ts === "string" ? new Date(ts) : ts;
  return d.toLocaleString("it-IT", {
    day: "2-digit",
    month: "short",
    hour: "2-digit",
    minute: "2-digit",
  });
}

export function ChatSection({
  clientId,
  phases,
  token,
  comments,
}: {
  clientId: string;
  phases: ClientView["phases"];
  token: string;
  comments: Comment[];
}) {
  const entities = buildEntityList(clientId, phases);
  const labelMap = buildLabelMap(entities);

  const [body, setBody] = useState("");
  const [selectedEntityId, setSelectedEntityId] = useState(clientId);
  const [error, setError] = useState<string | null>(null);
  const [, startTransition] = useTransition();
  const router = useRouter();
  const bottomRef = useRef<HTMLDivElement>(null);

  // Sort all comments chronologically
  const sorted = [...comments].sort(
    (a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime()
  );

  useEffect(() => {
    bottomRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [comments.length]);

  function handleSend(e: React.FormEvent) {
    e.preventDefault();
    const trimmed = body.trim();
    if (!trimmed) return;

    const selectedEntity = entities.find((en) => en.id === selectedEntityId);
    if (!selectedEntity) return;

    setError(null);
    startTransition(async () => {
      try {
        const res = await fetch("/api/client/comment", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            token,
            entity_type: selectedEntity.type,
            entity_id: selectedEntity.id,
            body: trimmed,
          }),
        });
        if (!res.ok) {
          const data = await res.json();
          setError(data.error ?? "Errore nell'invio");
          return;
        }
        setBody("");
        router.refresh();
      } catch {
        setError("Errore di rete");
      }
    });
  }

  return (
    <div className="flex flex-col rounded-xl border border-[#e5e7eb] overflow-hidden bg-white">
      {/* Chat feed */}
      <div className="flex-1 overflow-y-auto p-4 space-y-3 max-h-[480px] min-h-[200px]">
        {sorted.length === 0 && (
          <p className="text-sm text-[#71717a] italic text-center py-10">
            Nessun messaggio ancora. Scrivi qui sotto per iniziare.
          </p>
        )}
        {sorted.map((c) => {
          const isClient = c.author === "client";
          const entityLabel = labelMap.get(c.entity_id);
          const showTag = c.entity_id !== clientId && entityLabel;

          return (
            <div
              key={c.id}
              className={`flex flex-col gap-1 ${isClient ? "items-end" : "items-start"}`}
            >
              {/* Author + tag */}
              <div className={`flex items-center gap-2 ${isClient ? "flex-row-reverse" : ""}`}>
                <span
                  className={`text-[10px] font-bold uppercase tracking-wide px-2 py-0.5 rounded-full ${
                    isClient
                      ? "bg-[#DEF168] text-[#1A463C]"
                      : "bg-[#1A463C] text-white"
                  }`}
                >
                  {isClient ? "Tu" : "iamcavalli"}
                </span>
                {showTag && (
                  <span className="text-[10px] text-[#71717a] bg-[#f4f4f5] px-2 py-0.5 rounded-full truncate max-w-[180px]">
                    {entityLabel}
                  </span>
                )}
              </div>

              {/* Bubble */}
              <div
                className={`max-w-[75%] rounded-2xl px-4 py-2.5 text-sm leading-relaxed ${
                  isClient
                    ? "bg-[#1A463C] text-white rounded-tr-sm"
                    : "bg-[#f4f4f5] text-[#1a1a1a] rounded-tl-sm"
                }`}
              >
                {c.body}
              </div>

              {/* Timestamp */}
              <span className="text-[10px] text-[#71717a]">{formatTime(c.created_at)}</span>
            </div>
          );
        })}
        <div ref={bottomRef} />
      </div>

      {/* Divider */}
      <div className="border-t border-[#e5e7eb]" />

      {/* Input area */}
      <form onSubmit={handleSend} className="p-3 space-y-2 bg-[#fafafa]">
        {/* Entity selector */}
        <select
          value={selectedEntityId}
          onChange={(e) => setSelectedEntityId(e.target.value)}
          className="w-full text-xs border border-[#e5e7eb] rounded-lg px-3 py-1.5 bg-white text-[#1a1a1a] focus:outline-none focus:ring-2 focus:ring-[#1A463C]/30"
        >
          {entities.map((en) => (
            <option key={en.id} value={en.id}>
              {en.label}
            </option>
          ))}
        </select>

        <div className="flex gap-2">
          <textarea
            value={body}
            onChange={(e) => setBody(e.target.value)}
            onKeyDown={(e) => {
              if (e.key === "Enter" && !e.shiftKey) {
                e.preventDefault();
                handleSend(e as unknown as React.FormEvent);
              }
            }}
            placeholder="Scrivi un messaggio… (Invio per inviare)"
            rows={2}
            className="flex-1 text-sm border border-[#e5e7eb] rounded-lg px-3 py-2 bg-white resize-none focus:outline-none focus:ring-2 focus:ring-[#1A463C]/30"
          />
          <button
            type="submit"
            disabled={!body.trim()}
            className="self-end px-4 py-2 rounded-lg bg-[#1A463C] text-white text-sm font-semibold disabled:opacity-40 hover:bg-[#1A463C]/90 transition-colors"
          >
            Invia
          </button>
        </div>
        {error && <p className="text-xs text-red-600">{error}</p>}
      </form>
    </div>
  );
}