import { useState } from "react";
import { useParams, useNavigate } from "react-router-dom";
import { addTracker, getTrackerFields } from "../../lib/api";
import type { FilterGroup, TrackerField, AgentConfig } from "../../lib/types";
import FilterBuilder from "./FilterBuilder";

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

  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 [analystCommand, setAnalystCommand] = useState("claude");
  const [developerCommand, setDeveloperCommand] = useState("claude");
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  async function handleLoadFields() {
    if (!trackerId) return;
    setFieldsLoading(true);
    setError(null);
    try {
      const result = await getTrackerFields(Number(trackerId));
      setFields(result);
      setFieldsLoaded(true);
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : String(err));
    } finally {
      setFieldsLoading(false);
    }
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!projectId || trackerId === "") return;
    setError(null);
    setLoading(true);

    const agentConfig: AgentConfig = {
      analyst_command: analystCommand,
      analyst_args: [],
      developer_command: developerCommand,
      developer_args: [],
    };

    try {
      await addTracker(projectId, Number(trackerId), trackerLabel, pollingInterval, agentConfig, filters);
      navigate(`/projects/${projectId}`);
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : String(err));
    } finally {
      setLoading(false);
    }
  }

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

      <form onSubmit={handleSubmit} className="space-y-6">
        {/* 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>
        </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 command
            </label>
            <input
              type="text"
              value={analystCommand}
              onChange={(e) => setAnalystCommand(e.target.value)}
              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">
              Developer command
            </label>
            <input
              type="text"
              value={developerCommand}
              onChange={(e) => setDeveloperCommand(e.target.value)}
              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>

        {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}
            className="px-4 py-2 bg-blue-600 text-white rounded text-sm hover:bg-blue-700 disabled:opacity-50"
          >
            {loading ? "Adding..." : "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>
  );
}
