"use client";

import { useMemo, useState } from "react";
import { AtSign, MessageSquare, Pencil, Trash2 } from "lucide-react";
import { Avatar } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { useComments } from "@/hooks/use-comments";
import { useTeamPermissions } from "@/hooks/use-team-permissions";
import { useTeams } from "@/hooks/use-teams";
import { formatDate, formatRelativeDate } from "@/lib/utils";

interface CommentsPanelProps {
  entityType: "task" | "note";
  entityId: string;
  teamId: string | null;
  title?: string;
  allowCommentOverride?: boolean;
  allowModerateOverride?: boolean;
  placeholderOverride?: string;
}

export function CommentsPanel({
  entityType,
  entityId,
  teamId,
  title = "Comments",
  allowCommentOverride,
  allowModerateOverride,
  placeholderOverride,
}: CommentsPanelProps) {
  const { activeMembers } = useTeams();
  const { can } = useTeamPermissions(teamId);
  const { comments, loading, userId, createComment, updateComment, deleteComment } =
    useComments({
      entityType,
      entityId,
      teamId,
    });
  const canComment =
    allowCommentOverride ?? (!teamId || can("comments", "comment"));
  const canModerate =
    allowModerateOverride ?? (!!teamId && can("comments", "manage"));

  const [body, setBody] = useState("");
  const [mentionedUserIds, setMentionedUserIds] = useState<string[]>([]);
  const [submitting, setSubmitting] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [editingBody, setEditingBody] = useState("");
  const [editingMentionedUserIds, setEditingMentionedUserIds] = useState<string[]>(
    []
  );

  const mentionableMembers = useMemo(
    () =>
      activeMembers.filter((member) => member.user_id !== userId),
    [activeMembers, userId]
  );

  async function handleCreate() {
    if (!body.trim() || submitting) return;

    setSubmitting(true);
    await createComment({
      body,
      mentionedUserIds,
    });
    setBody("");
    setMentionedUserIds([]);
    setSubmitting(false);
  }

  async function handleSaveEdit() {
    if (!editingId || !editingBody.trim()) return;
    await updateComment(editingId, {
      body: editingBody,
      mentionedUserIds: editingMentionedUserIds,
    });
    setEditingId(null);
    setEditingBody("");
    setEditingMentionedUserIds([]);
  }

  return (
    <div className="space-y-4 rounded-2xl border border-border/60 bg-card p-4">
      <div className="flex items-center gap-2">
        <MessageSquare className="h-4 w-4 text-muted-foreground" />
        <h3 className="text-sm font-semibold">{title}</h3>
        <Badge variant="secondary">{comments.length}</Badge>
      </div>

      <div className="space-y-3">
        <Textarea
          value={body}
          onChange={(e) => setBody(e.target.value)}
          placeholder={
            placeholderOverride ||
            (teamId
              ? "Write an update, decision, or unblock request..."
              : "Add a private comment...")
          }
          className="min-h-[92px]"
          disabled={!canComment}
        />

        {!canComment && teamId && (
          <p className="text-xs text-muted-foreground">
            You can view this discussion, but only members with comment access can post updates.
          </p>
        )}

        {teamId && canComment && mentionableMembers.length > 0 && (
          <div className="space-y-2">
            <div className="flex items-center gap-2 text-xs text-muted-foreground">
              <AtSign className="h-3.5 w-3.5" />
              Mention teammates
            </div>
            <div className="flex flex-wrap gap-2">
              {mentionableMembers.map((member) => {
                const selected = mentionedUserIds.includes(member.user_id);
                const label =
                  member.profile?.full_name || member.profile?.email || "Team member";

                return (
                  <button
                    key={member.user_id}
                    type="button"
                    onClick={() =>
                      setMentionedUserIds((prev) =>
                        prev.includes(member.user_id)
                          ? prev.filter((id) => id !== member.user_id)
                          : [...prev, member.user_id]
                      )
                    }
                    className={`rounded-full border px-2.5 py-1 text-xs transition-colors ${
                      selected
                        ? "border-primary bg-primary/10 text-primary"
                        : "border-border bg-background text-muted-foreground hover:text-foreground"
                    }`}
                  >
                    @{label}
                  </button>
                );
              })}
            </div>
          </div>
        )}

        <div className="flex justify-end">
          <Button
            size="sm"
            onClick={() => void handleCreate()}
            disabled={!body.trim() || submitting || !canComment}
          >
            {submitting ? "Posting..." : "Post comment"}
          </Button>
        </div>
      </div>

      <div className="space-y-3">
        {loading ? (
          <p className="text-sm text-muted-foreground">Loading comments...</p>
        ) : comments.length === 0 ? (
          <p className="text-sm text-muted-foreground">
            No comments yet. Use this space for context, decisions, and handoffs.
          </p>
        ) : (
          comments.map((comment) => {
            const isAuthor = comment.user_id === userId;
            const canDeleteComment = isAuthor || canModerate;
            const authorName =
              comment.author?.full_name || comment.author?.email || "Unknown user";

            return (
              <div
                key={comment.id}
                className="rounded-2xl border border-border/60 bg-background/60 p-4"
              >
                <div className="flex items-start justify-between gap-3">
                  <div className="flex items-center gap-3">
                    <Avatar src={comment.author?.avatar_url} name={authorName} size="sm" />
                    <div>
                      <p className="text-sm font-medium">{authorName}</p>
                      <p
                        className="text-xs text-muted-foreground"
                        title={formatDate(comment.created_at)}
                      >
                        {formatRelativeDate(comment.created_at)}
                      </p>
                    </div>
                  </div>

                  {(isAuthor || canDeleteComment) && (
                    <div className="flex items-center gap-1">
                      {isAuthor && (
                        <Button
                          size="icon"
                          variant="ghost"
                          onClick={() => {
                            setEditingId(comment.id);
                            setEditingBody(comment.body);
                            setEditingMentionedUserIds(comment.mentioned_user_ids || []);
                          }}
                        >
                          <Pencil className="h-4 w-4" />
                        </Button>
                      )}
                      {canDeleteComment && (
                        <Button
                          size="icon"
                          variant="ghost"
                          onClick={() => void deleteComment(comment.id)}
                        >
                          <Trash2 className="h-4 w-4 text-destructive" />
                        </Button>
                      )}
                    </div>
                  )}
                </div>

                {editingId === comment.id ? (
                  <div className="mt-3 space-y-3">
                    <Textarea
                      value={editingBody}
                      onChange={(e) => setEditingBody(e.target.value)}
                      className="min-h-[88px]"
                    />
                    {teamId && mentionableMembers.length > 0 && (
                      <div className="flex flex-wrap gap-2">
                        {mentionableMembers.map((member) => {
                          const selected = editingMentionedUserIds.includes(
                            member.user_id
                          );
                          const label =
                            member.profile?.full_name ||
                            member.profile?.email ||
                            "Team member";

                          return (
                            <button
                              key={member.user_id}
                              type="button"
                              onClick={() =>
                                setEditingMentionedUserIds((prev) =>
                                  prev.includes(member.user_id)
                                    ? prev.filter((id) => id !== member.user_id)
                                    : [...prev, member.user_id]
                                )
                              }
                              className={`rounded-full border px-2.5 py-1 text-xs transition-colors ${
                                selected
                                  ? "border-primary bg-primary/10 text-primary"
                                  : "border-border bg-background text-muted-foreground hover:text-foreground"
                              }`}
                            >
                              @{label}
                            </button>
                          );
                        })}
                      </div>
                    )}
                    <div className="flex justify-end gap-2">
                      <Button
                        size="sm"
                        variant="ghost"
                        onClick={() => {
                          setEditingId(null);
                          setEditingBody("");
                          setEditingMentionedUserIds([]);
                        }}
                      >
                        Cancel
                      </Button>
                      <Button
                        size="sm"
                        onClick={() => void handleSaveEdit()}
                        disabled={!editingBody.trim()}
                      >
                        Save
                      </Button>
                    </div>
                  </div>
                ) : (
                  <>
                    <p className="mt-3 whitespace-pre-wrap text-sm leading-6">
                      {comment.body}
                    </p>

                    {comment.mentioned_users && comment.mentioned_users.length > 0 && (
                      <div className="mt-3 flex flex-wrap gap-2">
                        {comment.mentioned_users.map((user) => (
                          <Badge key={user.id} variant="outline">
                            @{user.full_name || user.email}
                          </Badge>
                        ))}
                      </div>
                    )}
                  </>
                )}
              </div>
            );
          })
        )}
      </div>
    </div>
  );
}
