'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import {
  Beaker,
  Play,
  Pause,
  CheckCircle,
  AlertCircle,
  Clock,
  ChevronRight,
  RefreshCw,
} from 'lucide-react';
import type { PipelineInfo } from '@/lib/pipeline-types';
import { listPipelines } from '@/lib/pipeline-api';

/**
 * Pipeline card component.
 */
function PipelineCard({ pipeline }: { pipeline: PipelineInfo }) {
  return (
    <Link
      href={`/pipelines/${pipeline.id}`}
      className="block bg-white rounded-xl border-2 border-gray-200 p-5 hover:shadow-lg hover:border-blue-400 transition-all"
    >
      <div className="flex items-start justify-between">
        <div className="flex items-center">
          <div
            className={`p-2 rounded-lg ${
              pipeline.is_enabled
                ? 'bg-green-100 text-green-600'
                : 'bg-gray-100 text-gray-600'
            }`}
          >
            <Beaker className="w-5 h-5" />
          </div>
          <div className="ml-3">
            <h3 className="font-bold text-gray-900">
              {pipeline.name}
            </h3>
            <p className="text-sm text-gray-500">v{pipeline.version}</p>
          </div>
        </div>
        <ChevronRight className="w-5 h-5 text-gray-400" />
      </div>

      <p className="mt-3 text-sm text-gray-600 line-clamp-2">
        {pipeline.description}
      </p>

      <div className="mt-4 flex items-center justify-between">
        <div className="flex items-center text-sm text-gray-600">
          <span className="font-medium mr-2">Stages:</span>
          {pipeline.stages.slice(0, 3).map((stage, i) => (
            <span
              key={stage}
              className="px-2 py-0.5 bg-gray-100 text-gray-700 rounded text-xs mr-1"
            >
              {stage}
            </span>
          ))}
          {pipeline.stages.length > 3 && (
            <span className="text-xs text-gray-500">
              +{pipeline.stages.length - 3} more
            </span>
          )}
        </div>

        <span
          className={`px-2 py-1 rounded-full text-xs font-semibold ${
            pipeline.is_enabled
              ? 'bg-green-100 text-green-700'
              : 'bg-gray-100 text-gray-600'
          }`}
        >
          {pipeline.is_enabled ? 'Enabled' : 'Disabled'}
        </span>
      </div>
    </Link>
  );
}

/**
 * Pipelines list page.
 */
export default function PipelinesPage() {
  const [pipelines, setPipelines] = useState<PipelineInfo[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [showDisabled, setShowDisabled] = useState(false);

  const fetchPipelines = async () => {
    setLoading(true);
    setError(null);
    try {
      const data = await listPipelines(!showDisabled);
      setPipelines(data);
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Failed to load pipelines');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchPipelines();
  }, [showDisabled]);

  return (
    <div className="h-full overflow-y-auto p-6">
      {/* Header */}
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">
            Pipelines
          </h1>
          <p className="text-gray-600 mt-1">
            Data processing pipelines for review analysis
          </p>
        </div>

        <div className="flex items-center space-x-3">
          {/* Show disabled toggle */}
          <label className="flex items-center cursor-pointer">
            <input
              type="checkbox"
              checked={showDisabled}
              onChange={(e) => setShowDisabled(e.target.checked)}
              className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
            />
            <span className="ml-2 text-sm text-gray-700">
              Show disabled
            </span>
          </label>

          {/* Refresh button */}
          <button
            onClick={fetchPipelines}
            disabled={loading}
            className="p-2 text-gray-500 hover:text-gray-700 hover:bg-gray-200 rounded-md disabled:opacity-50"
            title="Refresh"
          >
            <RefreshCw className={`w-5 h-5 ${loading ? 'animate-spin' : ''}`} />
          </button>
        </div>
      </div>

      {/* Content */}
      {error ? (
        <div className="text-center py-12">
          <AlertCircle className="w-12 h-12 text-red-500 mx-auto mb-4" />
          <p className="text-red-600">{error}</p>
          <button
            onClick={fetchPipelines}
            className="mt-4 px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700"
          >
            Retry
          </button>
        </div>
      ) : loading ? (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {[1, 2, 3].map((i) => (
            <div
              key={i}
              className="bg-white rounded-lg border border-gray-200 p-6 animate-pulse"
            >
              <div className="flex items-center">
                <div className="w-10 h-10 bg-gray-200 rounded-lg" />
                <div className="ml-3 flex-1">
                  <div className="h-4 w-32 bg-gray-200 rounded" />
                  <div className="h-3 w-16 bg-gray-200 rounded mt-2" />
                </div>
              </div>
              <div className="h-8 w-full bg-gray-200 rounded mt-4" />
              <div className="h-6 w-3/4 bg-gray-200 rounded mt-4" />
            </div>
          ))}
        </div>
      ) : pipelines.length === 0 ? (
        <div className="text-center py-12">
          <Beaker className="w-12 h-12 text-gray-400 mx-auto mb-4" />
          <p className="text-gray-500">No pipelines registered</p>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {pipelines.map((pipeline) => (
            <PipelineCard key={pipeline.id} pipeline={pipeline} />
          ))}
        </div>
      )}
    </div>
  );
}
