"use client";

import { useState, FormEvent, KeyboardEvent } from "react";
import { ListItem, addListComment } from "@/lib/api";
import { X, MessageSquare, User, Send } from "lucide-react";

interface ItemDetailModalProps {
  open: boolean;
  item: ListItem | null;
  listId: string;
  onClose: () => void;
  onItemUpdated?: () => void;
}

export function ItemDetailModal({ open, item, listId, onClose, onItemUpdated }: ItemDetailModalProps) {
  const [comment, setComment] = useState("");
  const [sending, setSending] = useState(false);
  const [comments, setComments] = useState<ListItem["comments"]>([]);

  if (!open || !item) return null;

  const currentComments = comments || item.comments || [];

  const handleAddComment = async (e?: FormEvent) => {
    e?.preventDefault();
    const trimmed = comment.trim();
    if (!trimmed || sending) return;
    setSending(true);
    try {
      const newComment = await addListComment(listId, item.id, trimmed);
      setComments([...currentComments, newComment]);
      setComment("");
      onItemUpdated?.();
    } catch (err) {
      console.error("Failed to add comment:", err);
    } finally {
      setSending(false);
    }
  };

  const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      handleAddComment();
    }
  };

  const assignedName =
    item.assigned_user?.name || item.assigned_user?.display_name || item.assigned_user?.email;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40" onClick={onClose}>
      <div
        className="w-full max-w-lg max-h-[80vh] bg-white rounded-lg shadow-2xl flex flex-col"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="flex items-center justify-between px-6 py-4 border-b border-gray-200">
          <h2 className="text-lg font-bold text-gray-900 truncate">{item.name}</h2>
          <button onClick={onClose} className="p-1 rounded text-gray-400 hover:text-gray-600 hover:bg-gray-100 transition-colors">
            <X size={20} />
          </button>
        </div>

        {/* Body */}
        <div className="flex-1 overflow-y-auto px-6 py-4 space-y-4">
          {/* Status & assignment */}
          <div className="flex items-center gap-4 flex-wrap">
            {item.status && (
              <span className="text-xs px-2 py-1 rounded-full bg-slack-purple/10 text-slack-purple font-medium">
                {item.status}
              </span>
            )}
            {assignedName && (
              <div className="flex items-center gap-1.5 text-sm text-gray-600">
                <div className="w-6 h-6 rounded-full bg-slack-purple text-white flex items-center justify-center text-xs font-bold">
                  {assignedName[0].toUpperCase()}
                </div>
                <span>{assignedName}</span>
              </div>
            )}
          </div>

          {/* Description */}
          {item.description && (
            <div>
              <h3 className="text-xs font-semibold text-gray-500 uppercase mb-1">Description</h3>
              <p className="text-sm text-gray-700">{item.description}</p>
            </div>
          )}

          {/* Comments */}
          <div>
            <h3 className="text-xs font-semibold text-gray-500 uppercase mb-2 flex items-center gap-1.5">
              <MessageSquare size={14} />
              Comments ({currentComments.length})
            </h3>
            <div className="space-y-3">
              {currentComments.map((c) => {
                const cname = c.user?.name || c.user?.display_name || c.user?.email || "User";
                return (
                  <div key={c.id} className="flex gap-2">
                    <div className="w-7 h-7 rounded-full bg-slack-aubergine text-white flex items-center justify-center text-xs font-bold flex-shrink-0">
                      {cname[0].toUpperCase()}
                    </div>
                    <div className="flex-1">
                      <div className="flex items-center gap-2">
                        <span className="text-sm font-medium text-gray-800">{cname}</span>
                        {c.created_at && (
                          <span className="text-xs text-gray-400">{new Date(c.created_at).toLocaleString()}</span>
                        )}
                      </div>
                      <p className="text-sm text-gray-600 mt-0.5">{c.text}</p>
                    </div>
                  </div>
                );
              })}
              {currentComments.length === 0 && (
                <p className="text-sm text-gray-400">No comments yet. Be the first to comment.</p>
              )}
            </div>
          </div>
        </div>

        {/* Comment input */}
        <div className="border-t border-gray-200 px-6 py-3">
          <form onSubmit={handleAddComment} className="flex items-end gap-2">
            <textarea
              value={comment}
              onChange={(e) => setComment(e.target.value)}
              onKeyDown={handleKeyDown}
              placeholder="Write a comment..."
              rows={1}
              className="flex-1 resize-none px-3 py-2 rounded-md border border-gray-300 focus:outline-none focus:ring-2 focus:ring-slack-purple focus:border-transparent text-sm min-h-[40px] max-h-[80px]"
              disabled={sending}
            />
            <button
              type="submit"
              disabled={sending || !comment.trim()}
              className="p-2 rounded-md bg-slack-purple text-white hover:bg-slack-darkpurple disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
            >
              <Send size={18} />
            </button>
          </form>
        </div>
      </div>
    </div>
  );
}