// components/projects.jsx — ProjectsPanel: lightweight name-based projects with assignment overview.
// Depends on: React (useState, useCallback, useEffect, useMemo), Card, get, post, del from api.js

// ── Hook: useProjects ────────────────────────────────────────
function useProjects() {
  const [projects, setProjects] = useState([]);
  const [loading, setLoading] = useState(true);

  const refresh = useCallback(async () => {
    setLoading(true);
    try {
      const data = await get("/dashboard/projects");
      setProjects(Array.isArray(data) ? data : []);
    } catch (e) {
      console.error("Failed to load projects:", e);
      setProjects([]);
    }
    setLoading(false);
  }, []);

  useEffect(() => { refresh(); }, [refresh]);

  return { projects, loading, refresh };
}

// ── AssignmentBadge — small count badge with icon ─────────────

function AssignmentBadge({ icon, label, count, color }) {
  return (
    <div className={`flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg border ${color}`}>
      <span className="text-sm">{icon}</span>
      <div className="text-left">
        <div className="text-xs font-semibold leading-none">{count}</div>
        <div className="text-[10px] leading-none mt-0.5 opacity-70">{label}</div>
      </div>
    </div>
  );
}

// ── ProjectCard — name + assignment overview ──────────────────

function ProjectCard({ project, onRefresh, isSelected, onSelect }) {
  const [showTickets, setShowTickets] = useState(false);
  const [tickets, setTickets] = useState(null);
  const [deleting, setDeleting] = useState(false);

  const ticketCount = project.ticket_count || 0;
  const envCount = (project.assigned_environments || []).length;
  const toolCount = (project.assigned_tools || []).length;
  const userCount = (project.assigned_users || []).length;

  const handleToggleTickets = async (e) => {
    e.stopPropagation();
    if (showTickets) { setShowTickets(false); return; }
    setShowTickets(true);
    if (tickets === null) {
      try {
        const data = await get(`/dashboard/projects/${project.id}/tickets`);
        setTickets(Array.isArray(data) ? data : []);
      } catch (err) {
        setTickets([]);
      }
    }
  };

  const handleDelete = async (e) => {
    e.stopPropagation();
    if (!confirm(`Delete project "${project.name}"?`)) return;
    setDeleting(true);
    try {
      await del(`/dashboard/projects/${project.id}`);
      onRefresh();
    } catch (err) {
      console.error("Delete failed:", err);
    }
    setDeleting(false);
  };

  const STATUS_CLASS = {
    done: "bg-emerald-100 text-emerald-700",
    in_progress: "bg-amber-100 text-amber-700",
    in_review: "bg-purple-100 text-purple-700",
    todo: "bg-blue-100 text-blue-700",
  };

  return (
    <div
      className={`bg-white rounded-lg border p-4 hover:shadow-md transition-shadow cursor-pointer text-left w-full ${
        isSelected ? "border-blue-400 bg-blue-50" : "border-gray-200"
      }`}
      onClick={() => onSelect(project.id)}
      role="button"
      tabIndex={0}
      aria-pressed={isSelected}
      aria-label={`Project ${project.name}`}
    >
      {/* Header: name + description */}
      <div className="flex items-center justify-between mb-3">
        <div className="flex items-center gap-2 min-w-0">
          <span className="text-lg">📋</span>
          <h4 className="font-semibold text-gray-900 truncate text-base">{project.name}</h4>
          {project.source_path && (
            <span className="text-xs text-gray-400 font-mono truncate max-w-[200px]" title={project.source_path}>
              {project.source_path}
            </span>
          )}
        </div>
        <button onClick={handleDelete} disabled={deleting}
          className="text-xs text-gray-400 hover:text-red-500 px-1.5 py-0.5 rounded hover:bg-red-50 transition-colors"
          title="Delete project">
          ✕
        </button>
      </div>

      {project.description && (
        <p className="text-xs text-gray-500 mb-3 truncate">{project.description}</p>
      )}

      {/* Assignment badges */}
      <div className="flex flex-wrap gap-2 mb-3">
        <AssignmentBadge icon="📝" label="Tasks" count={ticketCount} color="bg-blue-50 border-blue-200 text-blue-700" />
        <AssignmentBadge icon="🖥️" label="Envs" count={envCount} color="bg-emerald-50 border-emerald-200 text-emerald-700" />
        <AssignmentBadge icon="🔧" label="Tools" count={toolCount} color="bg-amber-50 border-amber-200 text-amber-700" />
        <AssignmentBadge icon="👤" label="Users" count={userCount} color="bg-purple-50 border-purple-200 text-purple-700" />
      </div>

      {/* Tool names */}
      {toolCount > 0 && (
        <div className="flex flex-wrap gap-1 mb-2">
          {project.assigned_tools.map(t => (
            <span key={t} className="text-xs px-2 py-0.5 bg-orange-50 text-orange-600 rounded-full border border-orange-200">{t}</span>
          ))}
        </div>
      )}

      {/* Environment names */}
      {envCount > 0 && (
        <div className="flex flex-wrap gap-1 mb-2">
          {project.assigned_environments.map(e => (
            <span key={e.id} className="text-xs px-2 py-0.5 bg-teal-50 text-teal-600 rounded-full border border-teal-200">
              {e.name} <span className="text-teal-400">({e.kind})</span>
            </span>
          ))}
        </div>
      )}

      {/* Actions */}
      <div className="flex items-center gap-2">
        <button onClick={handleToggleTickets}
          className="text-xs px-2.5 py-1 bg-gray-100 text-gray-600 rounded hover:bg-gray-200">
          {showTickets ? "Hide tickets" : `Show tickets (${ticketCount})`}
        </button>
      </div>

      {/* Inline ticket list */}
      {showTickets && (
        <div className="mt-3 space-y-1">
          {tickets === null && <p className="text-xs text-gray-400">Loading...</p>}
          {tickets && tickets.length === 0 && <p className="text-xs text-gray-400 italic">No tickets.</p>}
          {tickets && tickets.map(t => (
            <div key={t.id} className="flex items-center gap-2 text-xs p-2 bg-gray-50 rounded">
              <span className="font-mono text-gray-400">{t.id}</span>
              <span className={`px-1.5 py-0.5 rounded ${STATUS_CLASS[t.status] || "bg-gray-100 text-gray-600"}`}>{(t.status || "").replace("_", " ")}</span>
              <span className="truncate text-gray-700">{t.title || t.task}</span>
              {t.assigned_tool && <span className="text-indigo-500">{t.assigned_tool.tool}</span>}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// ── QuickCreateProject — form with multi-select for envs and tools ─

function QuickCreateProject({ onAdded, onCancel }) {
  const [name, setName] = useState("");
  const [description, setDescription] = useState("");
  const [defaultTool, setDefaultTool] = useState("");
  const [selectedEnvs, setSelectedEnvs] = useState([]);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState("");
  const [expandedSection, setExpandedSection] = useState("basic");
  const [environments, setEnvironments] = useState([]);
  const [loadingEnvs, setLoadingEnvs] = useState(false);

  const tools = ["aider", "claude-code", "vscode", "windsurf", "cursor", "roo-code", "cline", "browser"];

  // Load environments on mount
  useEffect(() => {
    const loadEnvs = async () => {
      setLoadingEnvs(true);
      try {
        const data = await get("/dashboard/environments");
        if (data?.environments) {
          setEnvironments(data.environments);
        }
      } catch (e) {
        console.error("Failed to load environments:", e);
      }
      setLoadingEnvs(false);
    };
    loadEnvs();
  }, []);

  const handleAddEnv = (envId) => {
    setSelectedEnvs(prev =>
      prev.includes(envId) ? prev.filter(e => e !== envId) : [...prev, envId]
    );
  };

  const handleCreate = async () => {
    if (!name.trim()) { setError("Project name is required"); return; }
    setSubmitting(true);
    setError("");
    try {
      const payload = { name: name.trim() };
      if (description.trim()) payload.description = description.trim();
      if (defaultTool) payload.default_tool = defaultTool;
      await post("/dashboard/projects", payload);
      // Note: Environment assignment would happen via a separate endpoint if needed
      onAdded();
    } catch (e) {
      setError(e.message || "Failed to create project");
    }
    setSubmitting(false);
  };

  return (
    <div className="rounded-xl shadow-sm border p-5 transition-colors bg-gradient-to-r from-blue-50 to-indigo-50 border-blue-200"
      style={{backgroundColor: "var(--dashboard-surface, #f9fafb)", borderColor: "var(--dashboard-border, #e5e7eb)"}}>

      <div className="flex items-center justify-between mb-4">
        <h3 className="text-sm font-semibold text-gray-900">Quick Create Project</h3>
      </div>

      <div className="space-y-3">
        {/* Basic info */}
        <div className="space-y-2">
          <label className="text-xs font-medium text-gray-600">Project Name *</label>
          <textarea
            value={name}
            onChange={e => setName(e.target.value)}
            placeholder="Project name (e.g. 24032026)..."
            rows="2"
            className="w-full px-3 py-2 border border-blue-200 rounded-lg text-sm focus:ring-2 focus:ring-blue-300 focus:outline-none resize-none"
            onKeyDown={e => e.key === "Enter" && e.ctrlKey && handleCreate()}
          />
          <p className="text-xs text-gray-500">Describe what this project is about</p>
        </div>

        {/* Description */}
        <div className="space-y-2">
          <label className="text-xs font-medium text-gray-600">Description (optional)</label>
          <input
            value={description}
            onChange={e => setDescription(e.target.value)}
            placeholder="e.g., AI proxy with semantic caching..."
            className="w-full px-3 py-1.5 border border-blue-200 rounded-lg text-sm focus:ring-2 focus:ring-blue-300 focus:outline-none"
          />
        </div>

        {/* Tool selection */}
        <div className="space-y-2">
          <label className="text-xs font-medium text-gray-600">Default Tool</label>
          <select
            value={defaultTool}
            onChange={e => setDefaultTool(e.target.value)}
            className="w-full px-3 py-1.5 border border-blue-200 rounded-lg text-sm">
            <option value="">No default tool</option>
            {tools.map(t => (
              <option key={t} value={t}>{t}</option>
            ))}
          </select>
        </div>

        {/* Multi-select Environments */}
        <div className="space-y-2">
          <button
            onClick={() => setExpandedSection(expandedSection === "envs" ? "" : "envs")}
            className="w-full text-left px-3 py-1.5 bg-blue-100 text-blue-900 rounded-lg text-xs font-medium hover:bg-blue-200 transition-colors flex items-center justify-between">
            <span>🖥️ Environments ({selectedEnvs.length})</span>
            <span>{expandedSection === "envs" ? "▼" : "▶"}</span>
          </button>
          {expandedSection === "envs" && (
            <div className="bg-blue-50 border border-blue-200 rounded-lg p-3 space-y-2 max-h-48 overflow-y-auto">
              {loadingEnvs ? (
                <p className="text-xs text-gray-500">Loading environments...</p>
              ) : environments.length === 0 ? (
                <p className="text-xs text-gray-500">No environments available</p>
              ) : (
                environments.map(env => (
                  <label key={env.id} className="flex items-center gap-2 p-1.5 hover:bg-blue-100 rounded cursor-pointer">
                    <input
                      type="checkbox"
                      checked={selectedEnvs.includes(env.id)}
                      onChange={() => handleAddEnv(env.id)}
                      className="rounded"
                    />
                    <span className="text-xs text-gray-700 flex-1">
                      {env.name} <span className="text-gray-500">({env.kind})</span>
                    </span>
                  </label>
                ))
              )}
            </div>
          )}
          {selectedEnvs.length > 0 && (
            <div className="flex flex-wrap gap-1">
              {selectedEnvs.map(envId => {
                const env = environments.find(e => e.id === envId);
                return (
                  <span key={envId} className="text-xs px-2 py-1 bg-teal-100 text-teal-700 rounded-full border border-teal-200 flex items-center gap-1">
                    {env?.name}
                    <button onClick={() => handleAddEnv(envId)} className="text-teal-500 hover:text-teal-700 font-bold">✕</button>
                  </span>
                );
              })}
            </div>
          )}
        </div>

        {/* Action buttons */}
        <div className="flex gap-2 pt-2">
          <button
            onClick={handleCreate}
            disabled={submitting || !name.trim()}
            className="flex-1 px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700 disabled:opacity-50 transition-colors">
            {submitting ? "Creating..." : "Create Project"}
          </button>
          <button
            onClick={onCancel}
            className="px-4 py-2 bg-gray-200 text-gray-700 text-sm font-medium rounded-lg hover:bg-gray-300 transition-colors">
            Cancel
          </button>
        </div>

        {/* Error message */}
        {error && <p className="text-xs text-red-600 font-medium">{error}</p>}
      </div>
    </div>
  );
}

// ── ProjectsPanel (main) ─────────────────────────────────────
function ProjectsPanel({ selectedProject, setSelectedProject }) {
  const { projects, loading, refresh } = useProjects();
  const [showAdd, setShowAdd] = useState(false);

  const stats = React.useMemo(() => ({
    total: projects.length,
    totalTickets: projects.reduce((sum, p) => sum + (p.ticket_count || 0), 0),
    totalEnvs: projects.reduce((sum, p) => sum + (p.assigned_environments || []).length, 0),
  }), [projects]);

  if (loading) {
    return <Card title="Projects"><p className="text-gray-500">Loading projects...</p></Card>;
  }

  return (
    <div className="space-y-4">
      {/* Stats */}
      <div className="grid grid-cols-3 gap-3">
        <div className="bg-white rounded-lg border p-3 text-center">
          <div className="text-2xl font-bold text-gray-900">{stats.total}</div>
          <div className="text-xs text-gray-500">Projects</div>
        </div>
        <div className="bg-white rounded-lg border p-3 text-center">
          <div className="text-2xl font-bold text-blue-600">{stats.totalTickets}</div>
          <div className="text-xs text-gray-500">Total Tasks</div>
        </div>
        <div className="bg-white rounded-lg border p-3 text-center">
          <div className="text-2xl font-bold text-emerald-600">{stats.totalEnvs}</div>
          <div className="text-xs text-gray-500">Environments</div>
        </div>
      </div>

      {/* Toolbar */}
      <div className="flex items-center justify-between flex-wrap gap-2">
        <div className="text-sm text-gray-500">{projects.length} project{projects.length !== 1 ? "s" : ""}</div>
        <div className="flex gap-2">
          <button onClick={() => setShowAdd(!showAdd)}
            className="px-3 py-1.5 bg-blue-600 text-white text-sm rounded hover:bg-blue-700">
            + New Project
          </button>
          <button onClick={refresh}
            className="px-3 py-1.5 bg-gray-100 text-gray-700 text-sm rounded hover:bg-gray-200">
            ↻ Refresh
          </button>
        </div>
      </div>

      {/* Quick Create form */}
      {showAdd && (
        <QuickCreateProject
          onAdded={() => { setShowAdd(false); refresh(); }}
          onCancel={() => setShowAdd(false)}
        />
      )}

      {/* Project cards */}
      <div className="space-y-3">
        {projects.length === 0 ? (
          <Card title="No projects">
            <p className="text-gray-500 text-sm">
              No projects yet. Click "+ New Project" to create one, or tickets will auto-create date-based projects.
            </p>
          </Card>
        ) : (
          projects.map(p => (
            <ProjectCard
              key={p.id}
              project={p}
              onRefresh={refresh}
              isSelected={selectedProject === p.id}
              onSelect={setSelectedProject}
            />
          ))
        )}
      </div>
    </div>
  );
}
