'use client';

import { useState, useEffect } from 'react';
import { useParams, useRouter } from 'next/navigation';
import Link from 'next/link';
import {
  ArrowLeft,
  Play,
  CheckCircle,
  Search,
  Loader,
  AlertCircle,
  ChevronRight,
} from 'lucide-react';
import type { PipelineDetail } from '@/lib/pipeline-types';
import { getPipeline, executePipeline } from '@/lib/pipeline-api';

interface Job {
  job_id: string;
  business_name: string;
  place_id: string;
  status: string;
  total_reviews: number;
  created_at: string;
  completed_at?: string;
}

/**
 * Run Pipeline page - select a job to process through the pipeline.
 */
export default function RunPipelinePage() {
  const params = useParams();
  const router = useRouter();
  const pipelineId = params.pipelineId as string;

  const [pipeline, setPipeline] = useState<PipelineDetail | null>(null);
  const [jobs, setJobs] = useState<Job[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedJob, setSelectedJob] = useState<Job | null>(null);
  const [executing, setExecuting] = useState(false);

  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);
      setError(null);

      try {
        // Fetch pipeline details
        const pipelineData = await getPipeline(pipelineId);
        setPipeline(pipelineData);

        // Fetch completed jobs
        const response = await fetch('/api/jobs/?status=completed&limit=100');
        if (!response.ok) throw new Error('Failed to fetch jobs');
        const jobsData = await response.json();
        // API returns { jobs: [...] }
        setJobs(jobsData.jobs || []);
      } catch (e) {
        setError(e instanceof Error ? e.message : 'Failed to load data');
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [pipelineId]);

  const handleExecute = async () => {
    if (!selectedJob || !pipeline) return;

    setExecuting(true);
    setError(null);

    try {
      const execution = await executePipeline(pipelineId, {
        job_id: selectedJob.job_id,
        // Always run all stages - they're sequential and depend on each other
        stages: pipeline.stages,
      });

      // Navigate to execution detail page
      router.push(`/pipelines/${pipelineId}/executions/${execution.execution_id}`);
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Failed to execute pipeline');
      setExecuting(false);
    }
  };

  // Filter jobs by search query
  const filteredJobs = jobs.filter((job) =>
    job.business_name.toLowerCase().includes(searchQuery.toLowerCase()) ||
    job.place_id.toLowerCase().includes(searchQuery.toLowerCase())
  );

  if (loading) {
    return (
      <div className="h-full overflow-y-auto p-6">
        <div className="animate-pulse">
          <div className="h-8 w-48 bg-gray-200 rounded mb-4" />
          <div className="h-4 w-96 bg-gray-200 rounded mb-8" />
          <div className="h-96 bg-gray-200 rounded-xl" />
        </div>
      </div>
    );
  }

  if (error && !pipeline) {
    return (
      <div className="h-full overflow-y-auto p-6">
        <Link
          href={`/pipelines/${pipelineId}`}
          className="inline-flex items-center text-sm text-gray-500 hover:text-gray-700 mb-6"
        >
          <ArrowLeft className="w-4 h-4 mr-1" />
          Back to Pipeline
        </Link>

        <div className="text-center py-12">
          <AlertCircle className="w-12 h-12 text-red-500 mx-auto mb-4" />
          <p className="text-red-600 mb-4">{error}</p>
        </div>
      </div>
    );
  }

  return (
    <div className="h-full overflow-y-auto p-6">
      {/* Navigation */}
      <Link
        href={`/pipelines/${pipelineId}`}
        className="inline-flex items-center text-sm text-gray-500 hover:text-gray-700 mb-6"
      >
        <ArrowLeft className="w-4 h-4 mr-1" />
        Back to Pipeline
      </Link>

      {/* Header */}
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-gray-900">Run Pipeline</h1>
        <p className="text-gray-600 mt-1">
          {pipeline?.name} - Select a completed job to process
        </p>
      </div>

      {error && (
        <div className="mb-6 p-4 bg-red-50 border border-red-200 rounded-lg">
          <p className="text-red-600">{error}</p>
        </div>
      )}

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Job Selection */}
        <div className="lg:col-span-2 bg-white rounded-xl border-2 border-gray-200 p-5">
          <h2 className="text-lg font-semibold text-gray-900 mb-4">
            Select Job
          </h2>

          {/* Search */}
          <div className="relative mb-4">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
            <input
              type="text"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              placeholder="Search jobs by business name..."
              className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>

          {/* Jobs List */}
          <div className="max-h-[500px] overflow-y-auto space-y-2">
            {filteredJobs.length === 0 ? (
              <div className="text-center py-8">
                <p className="text-gray-500">No completed jobs found</p>
              </div>
            ) : (
              filteredJobs.map((job, index) => (
                <div
                  key={job.job_id || `job-${index}`}
                  onClick={() => setSelectedJob(job)}
                  className={`p-4 rounded-lg border-2 cursor-pointer transition-all ${
                    selectedJob?.job_id === job.job_id
                      ? 'border-blue-500 bg-blue-50'
                      : 'border-gray-200 hover:border-gray-300 hover:bg-gray-50'
                  }`}
                >
                  <div className="flex items-center justify-between">
                    <div className="flex-1 min-w-0">
                      <h3 className="font-medium text-gray-900 truncate">
                        {job.business_name}
                      </h3>
                      <p className="text-xs text-gray-500 truncate mt-1">
                        {job.place_id}
                      </p>
                      <div className="mt-2 flex items-center text-xs text-gray-500 space-x-4">
                        <span>{job.total_reviews} reviews</span>
                        <span>
                          {new Date(job.completed_at || job.created_at).toLocaleDateString()}
                        </span>
                      </div>
                    </div>
                    {selectedJob?.job_id === job.job_id ? (
                      <CheckCircle className="w-6 h-6 text-blue-600 flex-shrink-0 ml-4" />
                    ) : (
                      <ChevronRight className="w-5 h-5 text-gray-300 flex-shrink-0 ml-4" />
                    )}
                  </div>
                </div>
              ))
            )}
          </div>
        </div>

        {/* Pipeline Info & Execute */}
        <div className="bg-white rounded-xl border-2 border-gray-200 p-5">
          <h2 className="text-lg font-semibold text-gray-900 mb-4">
            Pipeline Stages
          </h2>

          {/* Stages (read-only, informational) */}
          <div className="space-y-2 mb-6">
            {pipeline?.stages.map((stage, index) => (
              <div
                key={stage}
                className="flex items-center p-3 bg-gray-50 rounded-lg"
              >
                <div className="w-6 h-6 rounded-full flex items-center justify-center text-xs font-semibold mr-3 bg-blue-100 text-blue-700">
                  {index + 1}
                </div>
                <span className="font-medium text-gray-700">{stage}</span>
              </div>
            ))}
          </div>

          <p className="text-xs text-gray-500 mb-6">
            All stages will run sequentially. Each stage depends on the output of the previous stage.
          </p>

          {/* Summary */}
          <div className="p-4 bg-gray-50 rounded-lg mb-4">
            <h3 className="text-sm font-medium text-gray-700 mb-2">Summary</h3>
            <div className="space-y-2 text-sm">
              <div className="flex justify-between">
                <span className="text-gray-500">Selected Job:</span>
                <span className="font-medium text-gray-900 truncate max-w-[150px]">
                  {selectedJob?.business_name || 'None'}
                </span>
              </div>
              <div className="flex justify-between">
                <span className="text-gray-500">Reviews:</span>
                <span className="font-medium text-gray-900">
                  {selectedJob?.total_reviews || '-'}
                </span>
              </div>
              <div className="flex justify-between">
                <span className="text-gray-500">Stages:</span>
                <span className="font-medium text-gray-900">
                  {pipeline?.stages.length || 0}
                </span>
              </div>
            </div>
          </div>

          {/* Execute Button */}
          <button
            onClick={handleExecute}
            disabled={!selectedJob || executing}
            className="w-full flex items-center justify-center px-4 py-3 bg-blue-600 text-white font-medium rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
          >
            {executing ? (
              <>
                <Loader className="w-5 h-5 mr-2 animate-spin" />
                Starting...
              </>
            ) : (
              <>
                <Play className="w-5 h-5 mr-2" />
                Run Pipeline
              </>
            )}
          </button>
        </div>
      </div>
    </div>
  );
}
