'use client';

import { useEffect, useState } from 'react';
import { useParams, useRouter } from 'next/navigation';
import Link from 'next/link';
import { useJobs } from '@/contexts/JobsContext';
import { JobStatus } from '@/components/ScraperTest';

interface LogEntry {
  timestamp: string;
  level: string;
  message: string;
  source: string;
}

interface JobLogs {
  job_id: string;
  status: string;
  error_message: string | null;
  logs: LogEntry[];
  log_count: number;
}

function formatDuration(seconds: number): string {
  if (seconds < 60) return `${seconds.toFixed(1)}s`;
  const mins = Math.floor(seconds / 60);
  const secs = Math.round(seconds % 60);
  return `${mins}m ${secs}s`;
}

function extractBusinessName(job: JobStatus): string {
  if (job.business_name) return job.business_name;
  try {
    const urlObj = new URL(job.url);
    const query = urlObj.searchParams.get('query');
    return query ? decodeURIComponent(query) : 'Unknown Business';
  } catch {
    return 'Unknown Business';
  }
}

export default function JobDetailPage() {
  const params = useParams();
  const router = useRouter();
  const { jobs, refreshJobs } = useJobs();
  const [job, setJob] = useState<JobStatus | null>(null);
  const [logs, setLogs] = useState<JobLogs | null>(null);
  const [isLoadingLogs, setIsLoadingLogs] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);

  const jobId = params.id as string;

  // Find job from context or fetch it
  useEffect(() => {
    const foundJob = jobs.find(j => j.job_id === jobId);
    if (foundJob) {
      setJob(foundJob);
    } else {
      // Fetch job directly if not in context
      fetch(`/api/jobs/${jobId}`)
        .then(res => res.json())
        .then(data => setJob(data))
        .catch(console.error);
    }
  }, [jobId, jobs]);

  // Fetch logs
  useEffect(() => {
    if (!jobId) return;
    setIsLoadingLogs(true);
    fetch(`/api/jobs/${jobId}/logs`)
      .then(res => res.json())
      .then(data => setLogs(data))
      .catch(console.error)
      .finally(() => setIsLoadingLogs(false));
  }, [jobId]);

  const handleDelete = async () => {
    if (!confirm('Are you sure you want to delete this job?')) return;
    setIsDeleting(true);
    try {
      await fetch(`/api/jobs/${jobId}`, { method: 'DELETE' });
      await refreshJobs();
      router.push('/jobs');
    } catch (err) {
      console.error('Failed to delete job:', err);
    } finally {
      setIsDeleting(false);
    }
  };

  if (!job) {
    return (
      <div className="h-full flex items-center justify-center">
        <div className="w-8 h-8 border-4 border-blue-500 border-t-transparent rounded-full animate-spin" />
      </div>
    );
  }

  const businessName = extractBusinessName(job);
  const canViewAnalytics = job.reviews_count && job.reviews_count > 0;

  return (
    <div className="h-full overflow-y-auto p-6">
      {/* Breadcrumb */}
      <div className="mb-4 flex items-center gap-2 text-sm text-gray-500">
        <Link href="/jobs" className="hover:text-blue-600">Jobs</Link>
        <span>/</span>
        <span className="text-gray-900 font-medium">{jobId.slice(0, 8)}...</span>
      </div>

      {/* Header */}
      <div className="bg-white border-2 border-gray-200 rounded-xl p-6 mb-6">
        <div className="flex items-start justify-between mb-4">
          <div>
            <h1 className="text-2xl font-bold text-gray-900 mb-1">{businessName}</h1>
            {job.business_address && (
              <p className="text-gray-500 text-sm">{job.business_address}</p>
            )}
          </div>
          <span className={`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-sm font-semibold ${
            job.status === 'completed' ? 'bg-green-100 text-green-800' :
            job.status === 'partial' ? 'bg-orange-100 text-orange-800' :
            job.status === 'running' ? 'bg-blue-100 text-blue-800' :
            job.status === 'failed' ? 'bg-red-100 text-red-800' :
            'bg-gray-100 text-gray-800'
          }`}>
            {job.status === 'running' && (
              <div className="w-2 h-2 border border-current border-t-transparent rounded-full animate-spin" />
            )}
            {job.status.charAt(0).toUpperCase() + job.status.slice(1)}
          </span>
        </div>

        {/* Stats Grid */}
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
          {job.reviews_count !== null && (
            <div className="p-4 bg-blue-50 border border-blue-200 rounded-lg">
              <div className="text-2xl font-bold text-blue-800">{job.reviews_count.toLocaleString()}</div>
              <div className="text-xs font-medium text-blue-600">Reviews</div>
            </div>
          )}
          {job.scrape_time !== null && (
            <div className="p-4 bg-green-50 border border-green-200 rounded-lg">
              <div className="text-2xl font-bold text-green-800">{formatDuration(job.scrape_time)}</div>
              <div className="text-xs font-medium text-green-600">Duration</div>
            </div>
          )}
          {job.rating_snapshot !== null && (
            <div className="p-4 bg-yellow-50 border border-yellow-200 rounded-lg">
              <div className="text-2xl font-bold text-yellow-800 flex items-center gap-1">
                {job.rating_snapshot.toFixed(1)}
                <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
                  <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
                </svg>
              </div>
              <div className="text-xs font-medium text-yellow-600">Rating</div>
            </div>
          )}
          <div className="p-4 bg-gray-50 border border-gray-200 rounded-lg">
            <div className="text-sm font-bold text-gray-800">
              {new Date(job.created_at).toLocaleDateString()}
            </div>
            <div className="text-xs text-gray-500">
              {new Date(job.created_at).toLocaleTimeString()}
            </div>
            <div className="text-xs font-medium text-gray-600 mt-1">Created</div>
          </div>
        </div>

        {/* Actions */}
        <div className="flex gap-3">
          {canViewAnalytics && (
            <Link
              href={`/analytics/${jobId}`}
              className="flex-1 py-3 bg-blue-600 hover:bg-blue-700 text-white rounded-xl font-semibold transition-colors flex items-center justify-center gap-2"
            >
              <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
              </svg>
              View Analytics
            </Link>
          )}
          <a
            href={job.url}
            target="_blank"
            rel="noopener noreferrer"
            className="px-6 py-3 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-xl font-semibold transition-colors flex items-center justify-center gap-2"
          >
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
            </svg>
            Open in Maps
          </a>
          <button
            onClick={handleDelete}
            disabled={isDeleting || job.status === 'running'}
            className="px-6 py-3 bg-red-100 hover:bg-red-200 text-red-700 rounded-xl font-semibold transition-colors flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {isDeleting ? (
              <div className="w-5 h-5 border-2 border-red-500 border-t-transparent rounded-full animate-spin" />
            ) : (
              <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
              </svg>
            )}
            Delete
          </button>
        </div>

        {/* Error Message */}
        {job.error_message && (
          <div className="mt-4 p-4 bg-red-50 border border-red-200 rounded-lg">
            <div className="flex items-start gap-2">
              <svg className="w-5 h-5 text-red-600 flex-shrink-0 mt-0.5" fill="currentColor" viewBox="0 0 20 20">
                <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
              </svg>
              <div>
                <p className="font-semibold text-red-800">Error</p>
                <p className="text-sm text-red-700">{job.error_message}</p>
              </div>
            </div>
          </div>
        )}
      </div>

      {/* Logs Section */}
      <div className="bg-white border-2 border-gray-200 rounded-xl overflow-hidden">
        <div className="px-6 py-4 border-b border-gray-200 flex items-center justify-between">
          <h2 className="text-lg font-bold text-gray-900">Logs</h2>
          {logs && (
            <span className="text-sm text-gray-500">{logs.log_count} entries</span>
          )}
        </div>

        <div className="max-h-[500px] overflow-y-auto p-4 bg-gray-900">
          {isLoadingLogs ? (
            <div className="flex items-center justify-center py-8">
              <div className="w-8 h-8 border-4 border-blue-500 border-t-transparent rounded-full animate-spin" />
            </div>
          ) : logs && logs.logs.length > 0 ? (
            <div className="space-y-1 font-mono text-xs">
              {[...logs.logs]
                .sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime())
                .map((log, idx) => (
                  <div
                    key={idx}
                    className={`px-2 py-1 rounded ${
                      log.level === 'ERROR' ? 'bg-red-900/30 text-red-300' :
                      log.level === 'WARNING' ? 'bg-yellow-900/30 text-yellow-300' :
                      log.level === 'INFO' ? 'text-green-300' :
                      'text-gray-400'
                    }`}
                  >
                    <span className="text-gray-500">
                      {new Date(log.timestamp).toLocaleTimeString()}
                    </span>
                    {' '}
                    <span className={`font-bold ${
                      log.level === 'ERROR' ? 'text-red-400' :
                      log.level === 'WARNING' ? 'text-yellow-400' :
                      log.level === 'INFO' ? 'text-blue-400' :
                      'text-gray-500'
                    }`}>
                      [{log.level}]
                    </span>
                    {' '}
                    <span className={`${
                      log.source === 'browser' ? 'text-purple-400' : 'text-green-400'
                    }`}>
                      [{log.source}]
                    </span>
                    {' '}
                    <span>{log.message}</span>
                  </div>
                ))}
            </div>
          ) : (
            <div className="text-center text-gray-500 py-8">
              <p className="font-medium">No logs available</p>
              <p className="text-sm">Logs are recorded during scraping</p>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
