import { useState } from "react";
import { useParams, useNavigate } from "react-router-dom";
import { useEffect } from "react";
import {
  addTracker,
  getTrackerFields,
  listAgents,
  listTrackers,
  updateTracker,
} from "../../lib/api";
import { getErrorMessage } from "../../lib/errors";
import type { FilterGroup, TrackerField, Agent } from "../../lib/types";
import FilterBuilder from "./FilterBuilder";

export default function TrackerConfig() {
  const { projectId, trackerConfigId } = useParams<{ projectId: string; trackerConfigId: string }>();
  const navigate = useNavigate();
  const isEditing = Boolean(trackerConfigId);

  const [trackerId, setTrackerId] = useState<number | "">("");
  const [trackerLabel, setTrackerLabel] = useState("");
  const [pollingInterval, setPollingInterval] = useState(10);
  const [fields, setFields] = useState<TrackerField[]>([]);
  const [fieldsLoaded, setFieldsLoaded] = useState(false);
  const [fieldsLoading, setFieldsLoading] = useState(false);
  const [filters, setFilters] = useState<FilterGroup[]>([]);
  const [agents, setAgents] = useState<Agent[]>([]);
  const [analystAgentId, setAnalystAgentId] = useState("");
  const [developerAgentId, setDeveloperAgentId] = useState("");
  const [enabled, setEnabled] = useState(true);
  const [trackerStatus, setTrackerStatus] = useState<"valid" | "invalid">("valid");
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [initializing, setInitializing] = useState(false);

  function sortTrackerFields(input: TrackerField[]): TrackerField[] {
    return input
      .map((field) => ({
        ...field,
        values: [...field.values].sort((a, b) =>
          a.label.localeCompare(b.label, "fr", { sensitivity: "base" })
        ),
      }))
      .sort((a, b) =>
        a.label.localeCompare(b.label, "fr", { sensitivity: "base" })
      );
  }

  const analystAgents = agents.filter((agent) => agent.role === "analyst");
  const developerAgents = agents.filter((agent) => agent.role === "developer");

  useEffect(() => {
    async function loadAgents() {
      try {
        const all = await listAgents();
        setAgents(all);
      } catch (err: unknown) {
        setError(getErrorMessage(err));
      }
    }

    void loadAgents();
  }, []);

  useEffect(() => {
    if (isEditing) return;
    if (!analystAgentId && analystAgents.length > 0) {
      setAnalystAgentId(analystAgents[0].id);
    }
    if (!developerAgentId && developerAgents.length > 0) {
      setDeveloperAgentId(developerAgents[0].id);
    }
  }, [isEditing, analystAgentId, analystAgents, developerAgentId, developerAgents]);

  useEffect(() => {
    async function loadTrackerForEdit() {
      if (!projectId || !trackerConfigId) return;
      setInitializing(true);
      setError(null);
      try {
        const trackers = await listTrackers(projectId);
        const tracker = trackers.find((t) => t.id === trackerConfigId);
        if (!tracker) {
          setError("Tracker not found.");
          return;
        }
        setTrackerId(tracker.tracker_id);
        setTrackerLabel(tracker.tracker_label);
        setPollingInterval(tracker.polling_interval);
        setFilters(tracker.filters);
        setAnalystAgentId(tracker.analyst_agent_id ?? "");
        setDeveloperAgentId(tracker.developer_agent_id ?? "");
        setEnabled(tracker.enabled);
        setTrackerStatus(tracker.status === "invalid" ? "invalid" : "valid");

        const trackerFields = await getTrackerFields(tracker.tracker_id);
        setFields(sortTrackerFields(trackerFields));
        setFieldsLoaded(true);
      } catch (err: unknown) {
        setError(getErrorMessage(err));
      } finally {
        setInitializing(false);
      }
    }

    void loadTrackerForEdit();
  }, [projectId, trackerConfigId]);

  async function handleLoadFields() {
    if (!trackerId) return;
    setFieldsLoading(true);
    setError(null);
    try {
      const result = await getTrackerFields(Number(trackerId));
      setFields(sortTrackerFields(result));
      setFieldsLoaded(true);
    } catch (err: unknown) {
      setError(getErrorMessage(err));
    } finally {
      setFieldsLoading(false);
    }
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!projectId || trackerId === "") return;
    if (!analystAgentId || !developerAgentId) {
      setError("Please select one analyst agent and one developer agent.");
      return;
    }

    setError(null);
    setLoading(true);

    try {
      if (isEditing && trackerConfigId) {
        await updateTracker(
          trackerConfigId,
          Number(trackerId),
          trackerLabel,
          pollingInterval,
          analystAgentId,
          developerAgentId,
          filters,
          enabled
        );
      } else {
        await addTracker(
          projectId,
          Number(trackerId),
          trackerLabel,
          pollingInterval,
          analystAgentId,
          developerAgentId,
          filters
        );
      }
      navigate(`/projects/${projectId}`);
    } catch (err: unknown) {
      setError(getErrorMessage(err));
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="max-w-2xl mx-auto p-8">
      <h2 className="text-xl font-bold mb-6">
        {isEditing ? "Edit tracker" : "Add tracker"}
      </h2>

      <form onSubmit={handleSubmit} className="space-y-6">
        {initializing && (
          <div className="text-sm text-gray-500">Loading tracker...</div>
        )}

        {analystAgents.length === 0 || developerAgents.length === 0 ? (
          <div className="rounded border border-amber-200 bg-amber-50 p-3 text-sm text-amber-700">
            You need at least one analyst agent and one developer agent before creating a tracker.
          </div>
        ) : null}

        {isEditing && trackerStatus === "invalid" && (
          <div className="rounded border border-red-200 bg-red-50 p-3 text-sm text-red-700">
            This tracker is invalid. Select valid agents and save to reactivate it.
          </div>
        )}

        {/* Basic fields */}
        <div className="bg-white rounded-lg border border-gray-200 p-4 space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Tracker ID
            </label>
            <div className="flex gap-2">
              <input
                type="number"
                value={trackerId}
                onChange={(e) => {
                  setTrackerId(e.target.value === "" ? "" : Number(e.target.value));
                  setFieldsLoaded(false);
                  setFields([]);
                }}
                required
                min={1}
                className="w-40 border border-gray-300 rounded px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                placeholder="e.g. 42"
              />
              <button
                type="button"
                onClick={handleLoadFields}
                disabled={!trackerId || fieldsLoading}
                className="px-4 py-2 bg-blue-600 text-white rounded text-sm hover:bg-blue-700 disabled:opacity-50"
              >
                {fieldsLoading ? "Loading..." : "Load tracker fields"}
              </button>
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Label
            </label>
            <input
              type="text"
              value={trackerLabel}
              onChange={(e) => setTrackerLabel(e.target.value)}
              required
              placeholder="e.g. Bugs"
              className="w-full border border-gray-300 rounded px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Polling interval (minutes)
            </label>
            <input
              type="number"
              value={pollingInterval}
              onChange={(e) => setPollingInterval(Number(e.target.value))}
              required
              min={1}
              className="w-40 border border-gray-300 rounded px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>

          {isEditing && (
            <label className="flex items-center gap-2 text-sm text-gray-700">
              <input
                type="checkbox"
                checked={enabled}
                onChange={(e) => setEnabled(e.target.checked)}
              />
              Tracker enabled
            </label>
          )}
        </div>

        {/* Filter builder */}
        {fieldsLoaded && (
          <div>
            <h3 className="text-sm font-semibold text-gray-700 mb-2">Filters</h3>
            <FilterBuilder
              groups={filters}
              onChange={setFilters}
              availableFields={fields}
            />
          </div>
        )}

        {/* Agent config */}
        <div className="bg-white rounded-lg border border-gray-200 p-4 space-y-4">
          <h3 className="text-sm font-semibold text-gray-700">Agent configuration</h3>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Analyst agent
            </label>
            <select
              value={analystAgentId}
              onChange={(e) => setAnalystAgentId(e.target.value)}
              required
              className="w-full border border-gray-300 rounded px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              <option value="">Select an analyst agent</option>
              {analystAgents.map((agent) => (
                <option key={agent.id} value={agent.id}>
                  {agent.name} ({agent.tool === "codex" ? "Codex" : "Claude Code"})
                </option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Developer agent
            </label>
            <select
              value={developerAgentId}
              onChange={(e) => setDeveloperAgentId(e.target.value)}
              required
              className="w-full border border-gray-300 rounded px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              <option value="">Select a developer agent</option>
              {developerAgents.map((agent) => (
                <option key={agent.id} value={agent.id}>
                  {agent.name} ({agent.tool === "codex" ? "Codex" : "Claude Code"})
                </option>
              ))}
            </select>
          </div>
        </div>

        {error && (
          <div className="text-red-600 text-sm bg-red-50 border border-red-200 rounded p-2">
            {error}
          </div>
        )}

        <div className="flex gap-2">
          <button
            type="submit"
            disabled={loading || initializing}
            className="px-4 py-2 bg-blue-600 text-white rounded text-sm hover:bg-blue-700 disabled:opacity-50"
          >
            {loading ? "Saving..." : isEditing ? "Save tracker" : "Add tracker"}
          </button>
          <button
            type="button"
            onClick={() => navigate(`/projects/${projectId}`)}
            className="px-4 py-2 bg-gray-200 rounded text-sm hover:bg-gray-300"
          >
            Cancel
          </button>
        </div>
      </form>
    </div>
  );
}
