"use client";

import { useEffect, useState, useCallback } from "react";
import { useRouter, useParams } from "next/navigation";
import { useAuth } from "@/lib/auth";
import { useTranslation } from "@/lib/i18n";
import {
  getTask,
  Task,
  Subtask,
  CollabRequest,
  getSubtasks,
  createSubtask,
  updateSubtask,
  deleteSubtask,
  getCollaborationHistory,
  sendCollabRequest,
  searchUsers,
} from "@/lib/api";
import CollabBackButton from "@/components/features/CollabBackButton";
import CollabActionButtons from "@/components/features/CollabActionButtons";
import IconButton from "@/components/features/IconButton";

interface UserResult {
  id: string;
  name: string;
  email: string;
  avatar_url: string | null;
}

function UserAvatar({ name, avatarUrl, size = "sm" }: { name: string; avatarUrl?: string | null; size?: "sm" | "md" }) {
  const sz = size === "md" ? "w-10 h-10 text-sm" : "w-8 h-8 text-xs";
  const initials = name
    .split(" ")
    .map((n) => n[0])
    .join("")
    .toUpperCase()
    .slice(0, 2);
  if (avatarUrl) {
    return <img src={avatarUrl} alt={name} className={`${sz} rounded-full object-cover`} />;
  }
  const colors = ["bg-blue-500", "bg-green-500", "bg-purple-500", "bg-orange-500", "bg-pink-500", "bg-teal-500"];
  const color = colors[name.charCodeAt(0) % colors.length];
  return (
    <div className={`${sz} rounded-full ${color} text-white flex items-center justify-center font-medium`}>
      {initials}
    </div>
  );
}

function UserSearchDropdown({
  token,
  onSelect,
  placeholder,
}: {
  token: string;
  onSelect: (user: UserResult) => void;
  placeholder: string;
}) {
  const [query, setQuery] = useState("");
  const [results, setResults] = useState<UserResult[]>([]);
  const [searching, setSearching] = useState(false);

  useEffect(() => {
    if (query.length < 2) {
      setResults([]);
      return;
    }
    const timer = setTimeout(async () => {
      setSearching(true);
      try {
        const res = await searchUsers(token, query);
        setResults(res.data || []);
      } catch {
        setResults([]);
      } finally {
        setSearching(false);
      }
    }, 300);
    return () => clearTimeout(timer);
  }, [query, token]);

  return (
    <div className="relative">
      <input
        type="text"
        value={query}
        onChange={(e) => setQuery(e.target.value)}
        placeholder={placeholder}
        className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
      />
      {searching && (
        <div className="absolute right-3 top-2.5">
          <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600" />
        </div>
      )}
      {results.length > 0 && (
        <div className="absolute z-10 w-full mt-1 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg max-h-48 overflow-y-auto">
          {results.map((user) => (
            <button
              key={user.id}
              onClick={() => {
                onSelect(user);
                setQuery("");
                setResults([]);
              }}
              className="w-full flex items-center gap-2 px-3 py-2 hover:bg-gray-100 dark:hover:bg-gray-700 text-left"
            >
              <UserAvatar name={user.name} avatarUrl={user.avatar_url} />
              <div>
                <div className="text-sm font-medium">{user.name}</div>
                <div className="text-xs text-gray-500">{user.email}</div>
              </div>
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

export default function CollaboratePage() {
  const { token, user } = useAuth();
  const { t } = useTranslation();
  const router = useRouter();
  const params = useParams();
  const id = params.id as string;

  const [task, setTask] = useState<Task | null>(null);
  const [subtasks, setSubtasks] = useState<Subtask[]>([]);
  const [history, setHistory] = useState<CollabRequest[]>([]);
  const [assignees, setAssignees] = useState<UserResult[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  const [showAssignSearch, setShowAssignSearch] = useState(false);
  const [showTransferSearch, setShowTransferSearch] = useState(false);
  const [transferMessage, setTransferMessage] = useState("");
  const [newSubtaskTitle, setNewSubtaskTitle] = useState("");
  const [showSubtaskForm, setShowSubtaskForm] = useState(false);
  const [subtaskAssignee, setSubtaskAssignee] = useState<UserResult | null>(null);
  const [actionLoading, setActionLoading] = useState(false);

  const loadAll = useCallback(async () => {
    if (!token || !id) return;
    setLoading(true);
    try {
      const [taskData, subtasksData, historyData] = await Promise.all([
        getTask(token, id),
        getSubtasks(token, id),
        getCollaborationHistory(token, id),
      ]);
      setTask(taskData);
      setSubtasks(subtasksData.data || []);
      setHistory(historyData.data || []);

      const assignedIds: string[] = taskData.assigned_to || [];
      if (assignedIds.length > 0) {
        try {
          const usersRes = await searchUsers(token, "");
          const knownUsers = new Map<string, UserResult>();
          (historyData.data || []).forEach((h: CollabRequest) => {
            if (h.from_user_id && h.from_name) knownUsers.set(h.from_user_id, { id: h.from_user_id, name: h.from_name, email: "", avatar_url: null });
            if (h.to_user_id && h.to_name) knownUsers.set(h.to_user_id, { id: h.to_user_id, name: h.to_name, email: "", avatar_url: null });
          });
          (usersRes.data || []).forEach((u: UserResult) => knownUsers.set(u.id, u));
          setAssignees(assignedIds.map((uid) => knownUsers.get(uid) || { id: uid, name: uid.slice(0, 8), email: "", avatar_url: null }));
        } catch {
          setAssignees(assignedIds.map((uid) => ({ id: uid, name: uid.slice(0, 8), email: "", avatar_url: null })));
        }
      } else {
        setAssignees([]);
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : t("tasks.loadError"));
    } finally {
      setLoading(false);
    }
  }, [token, id, t]);

  useEffect(() => {
    if (!token) {
      router.replace("/login");
      return;
    }
    loadAll();
  }, [token, router, loadAll]);

  async function handleAssign(selectedUser: UserResult) {
    if (!token || !id || !user) return;
    setActionLoading(true);
    try {
      await sendCollabRequest(token, id, {
        from_user_id: user.id,
        to_user_id: selectedUser.id,
        type: "assign",
        message: "",
      });
      setShowAssignSearch(false);
      await loadAll();
    } catch (err) {
      setError(err instanceof Error ? err.message : t("common.error"));
    } finally {
      setActionLoading(false);
    }
  }

  async function handleTransfer(selectedUser: UserResult) {
    if (!token || !id || !user) return;
    setActionLoading(true);
    try {
      await sendCollabRequest(token, id, {
        from_user_id: user.id,
        to_user_id: selectedUser.id,
        type: "transfer",
        message: transferMessage,
      });
      setShowTransferSearch(false);
      setTransferMessage("");
      await loadAll();
    } catch (err) {
      setError(err instanceof Error ? err.message : t("common.error"));
    } finally {
      setActionLoading(false);
    }
  }

  async function handleClaim() {
    if (!token || !id || !user) return;
    setActionLoading(true);
    try {
      await sendCollabRequest(token, id, {
        from_user_id: user.id,
        type: "claim",
      });
      await loadAll();
    } catch (err) {
      setError(err instanceof Error ? err.message : t("common.error"));
    } finally {
      setActionLoading(false);
    }
  }

  async function handleAddSubtask() {
    if (!token || !id || !newSubtaskTitle.trim()) return;
    setActionLoading(true);
    try {
      await createSubtask(token, id, {
        title: newSubtaskTitle.trim(),
        assigned_to: subtaskAssignee?.id,
      });
      setNewSubtaskTitle("");
      setSubtaskAssignee(null);
      setShowSubtaskForm(false);
      await loadAll();
    } catch (err) {
      setError(err instanceof Error ? err.message : t("common.error"));
    } finally {
      setActionLoading(false);
    }
  }

  async function handleToggleSubtask(subtask: Subtask) {
    if (!token || !id) return;
    const newStatus = subtask.status === "done" || subtask.status === "completed" ? "pending" : "done";
    try {
      await updateSubtask(token, id, subtask.id, { status: newStatus });
      await loadAll();
    } catch (err) {
      setError(err instanceof Error ? err.message : t("common.error"));
    }
  }

  async function handleDeleteSubtask(subtaskId: string) {
    if (!token || !id) return;
    try {
      await deleteSubtask(token, id, subtaskId);
      await loadAll();
    } catch (err) {
      setError(err instanceof Error ? err.message : t("common.error"));
    }
  }

  if (!token) return null;

  if (loading) {
    return (
      <div className="flex justify-center py-12">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600" />
      </div>
    );
  }

  if (error && !task) {
    return (
      <div className="text-center py-12">
        <p className="text-red-500">{error}</p>
        <button onClick={() => router.back()} className="mt-4 text-blue-600 hover:underline">
          {t("common.back")}
        </button>
      </div>
    );
  }

  const subtasksDone = subtasks.filter((s) => s.status === "done" || s.status === "completed").length;
  const subtasksTotal = subtasks.length;
  const progressPct = subtasksTotal > 0 ? Math.round((subtasksDone / subtasksTotal) * 100) : 0;

  const collabTypeLabels: Record<string, { icon: string; label: string; color: string }> = {
    assign: { icon: "+", label: t("collab.assigned"), color: "text-blue-600" },
    transfer: { icon: "->", label: t("collab.transferred"), color: "text-orange-600" },
    claim: { icon: "!", label: t("collab.claimed"), color: "text-green-600" },
    collaborate: { icon: "&", label: t("collab.collaborated"), color: "text-purple-600" },
  };

  return (
    <div className="max-w-lg mx-auto space-y-4 pb-20 px-4 sm:px-0">
      {/* Header */}
      <div className="flex items-center gap-2">
        <CollabBackButton
          onClick={() => router.push(`/tasks/${id}`)}
          label={t("common.back")}
        />
        <h1 className="text-lg font-bold flex-1 truncate">{t("collab.title")}</h1>
      </div>

      {/* Task title */}
      {task && (
        <div className="bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-700 rounded-xl p-4">
          <h2 className="font-semibold text-base">{task.title}</h2>
          {task.description && <p className="text-sm text-gray-500 mt-1 line-clamp-2">{task.description}</p>}
        </div>
      )}

      {error && (
        <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-3 text-sm text-red-600 dark:text-red-400">
          {error}
          <button onClick={() => setError("")} className="ml-2 underline">
            OK
          </button>
        </div>
      )}

      {/* Assignees section */}
      <div className="bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-700 rounded-xl p-4">
        <h3 className="text-sm font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider mb-3">
          {t("collab.assignees")}
        </h3>

        {assignees.length > 0 ? (
          <div className="flex flex-wrap gap-2 mb-3">
            {assignees.map((a) => (
              <div key={a.id} className="flex items-center gap-2 bg-gray-50 dark:bg-gray-800 rounded-full px-3 py-1.5">
                <UserAvatar name={a.name} avatarUrl={a.avatar_url} />
                <span className="text-sm font-medium">{a.name}</span>
              </div>
            ))}
          </div>
        ) : (
          <p className="text-sm text-gray-400 mb-3">{t("collab.noAssignees")}</p>
        )}

        {/* Action buttons - icon only with tooltips */}
        <CollabActionButtons
          onAssign={() => {
            setShowAssignSearch(!showAssignSearch);
            setShowTransferSearch(false);
          }}
          onTransfer={() => {
            setShowTransferSearch(!showTransferSearch);
            setShowAssignSearch(false);
          }}
          onClaim={handleClaim}
          disabled={actionLoading}
          t={t}
        />

        {/* Assign search dropdown */}
        {showAssignSearch && (
          <div className="mt-3">
            <UserSearchDropdown
              token={token!}
              onSelect={handleAssign}
              placeholder={t("collab.searchUser")}
            />
          </div>
        )}

        {/* Transfer search dropdown */}
        {showTransferSearch && (
          <div className="mt-3 space-y-2">
            <UserSearchDropdown
              token={token!}
              onSelect={handleTransfer}
              placeholder={t("collab.searchUser")}
            />
            <textarea
              value={transferMessage}
              onChange={(e) => setTransferMessage(e.target.value)}
              placeholder={t("collab.transferMessage")}
              rows={2}
              className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 focus:ring-2 focus:ring-blue-500"
            />
          </div>
        )}
      </div>

      {/* Subtasks section */}
      <div className="bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-700 rounded-xl p-4">
        <div className="flex items-center justify-between mb-3">
          <h3 className="text-sm font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">
            {t("collab.subtasks")}
          </h3>
          {subtasksTotal > 0 && (
            <span className="text-xs text-gray-500">
              {subtasksDone}/{subtasksTotal}
            </span>
          )}
        </div>

        {subtasksTotal > 0 && (
          <div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2 mb-3">
            <div
              className="bg-green-500 h-2 rounded-full transition-all duration-300"
              style={{ width: `${progressPct}%` }}
            />
          </div>
        )}

        <div className="space-y-2 mb-3">
          {subtasks.map((sub) => {
            const subDone = sub.status === "done" || sub.status === "completed";
            return (
              <div
                key={sub.id}
                className="flex items-center gap-2 group"
              >
                <button
                  onClick={() => handleToggleSubtask(sub)}
                  className={`flex-shrink-0 w-5 h-5 rounded border-2 flex items-center justify-center transition-colors ${
                    subDone
                      ? "bg-green-500 border-green-500 text-white"
                      : "border-gray-300 dark:border-gray-600 hover:border-green-400"
                  }`}
                >
                  {subDone && (
                    <svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={3}>
                      <path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" />
                    </svg>
                  )}
                </button>
                <span className={`flex-1 text-sm ${subDone ? "line-through text-gray-400" : ""}`}>
                  {sub.title}
                </span>
                {sub.assignee_name && (
                  <span className="text-xs text-gray-400 bg-gray-100 dark:bg-gray-800 px-2 py-0.5 rounded-full">
                    {sub.assignee_name}
                  </span>
                )}
                <button
                  onClick={() => handleDeleteSubtask(sub.id)}
                  title={t("tasks.delete")}
                  className="opacity-0 group-hover:opacity-100 text-red-400 hover:text-red-600 transition-opacity p-1 rounded"
                >
                  <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                    <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
                  </svg>
                </button>
              </div>
            );
          })}
        </div>

        {subtasks.length === 0 && (
          <p className="text-sm text-gray-400 mb-3">{t("collab.noSubtasks")}</p>
        )}

        {showSubtaskForm ? (
          <div className="space-y-2 border-t border-gray-100 dark:border-gray-700 pt-3">
            <input
              type="text"
              value={newSubtaskTitle}
              onChange={(e) => setNewSubtaskTitle(e.target.value)}
              placeholder={t("collab.subtaskTitle")}
              className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 focus:ring-2 focus:ring-blue-500"
              onKeyDown={(e) => {
                if (e.key === "Enter" && newSubtaskTitle.trim()) handleAddSubtask();
              }}
              autoFocus
            />
            {subtaskAssignee && (
              <div className="flex items-center gap-2 text-sm">
                <UserAvatar name={subtaskAssignee.name} avatarUrl={subtaskAssignee.avatar_url} />
                <span>{subtaskAssignee.name}</span>
                <button onClick={() => setSubtaskAssignee(null)} className="text-gray-400 hover:text-red-500">
                  <svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                    <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
                  </svg>
                </button>
              </div>
            )}
            {!subtaskAssignee && (
              <UserSearchDropdown
                token={token!}
                onSelect={(user) => setSubtaskAssignee(user)}
                placeholder={t("collab.assignSubtask")}
              />
            )}
            <div className="flex gap-2">
              <IconButton
                icon={
                  <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                    <path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" />
                  </svg>
                }
                label={t("collab.addBtn")}
                onClick={handleAddSubtask}
                disabled={!newSubtaskTitle.trim() || actionLoading}
                variant="primary"
                size="md"
              />
              <IconButton
                icon={
                  <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                    <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
                  </svg>
                }
                label={t("tasks.form.cancel")}
                onClick={() => {
                  setShowSubtaskForm(false);
                  setNewSubtaskTitle("");
                  setSubtaskAssignee(null);
                }}
                variant="default"
                size="md"
              />
            </div>
          </div>
        ) : (
          <IconButton
            icon={
              <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M12 4v16m8-8H4" />
              </svg>
            }
            label={t("collab.addSubtask")}
            onClick={() => setShowSubtaskForm(true)}
            variant="primary"
            size="md"
          />
        )}
      </div>

      {/* Collaboration history */}
      <div className="bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-700 rounded-xl p-4">
        <h3 className="text-sm font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider mb-3">
          {t("collab.history")}
        </h3>

        {history.length > 0 ? (
          <div className="space-y-3">
            {history.map((h) => {
              const info = collabTypeLabels[h.type] || collabTypeLabels.assign;
              const date = new Date(h.created_at);
              const dateStr = date.toLocaleDateString("cs-CZ", {
                day: "numeric",
                month: "numeric",
                hour: "2-digit",
                minute: "2-digit",
              });
              return (
                <div key={h.id} className="flex items-start gap-3 text-sm">
                  <div className={`flex-shrink-0 w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold ${info.color} bg-gray-100 dark:bg-gray-800`}>
                    {info.icon}
                  </div>
                  <div className="flex-1 min-w-0">
                    <div>
                      <span className="font-medium">{h.from_name || t("collab.system")}</span>
                      <span className="text-gray-500"> {info.label} </span>
                      {h.to_name && <span className="font-medium">{h.to_name}</span>}
                    </div>
                    {h.message && (
                      <p className="text-gray-500 text-xs mt-0.5 italic">&quot;{h.message}&quot;</p>
                    )}
                    <div className="flex items-center gap-2 mt-0.5">
                      <span className="text-xs text-gray-400">{dateStr}</span>
                      <span
                        className={`text-xs px-1.5 py-0.5 rounded-full ${
                          h.status === "accepted"
                            ? "bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400"
                            : h.status === "rejected"
                            ? "bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400"
                            : "bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400"
                        }`}
                      >
                        {h.status === "accepted" ? t("collab.statusAccepted") : h.status === "rejected" ? t("collab.statusRejected") : t("collab.statusPending")}
                      </span>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        ) : (
          <p className="text-sm text-gray-400">{t("collab.noHistory")}</p>
        )}
      </div>
    </div>
  );
}
