'use client';

import { useState, useEffect } from 'react';
import { toast } from 'react-hot-toast';
import { History, Download, Eye, Trash2, Filter, Search } from 'lucide-react';
import { jobsApi, assetsApi } from '@/lib/api';
import { format } from 'date-fns';

const moduleFilters = [
  { value: '', label: 'All Modules' },
  { value: 'image_generation', label: 'Image Generation' },
  { value: 'image_upscaling', label: 'Image Upscaling' },
  { value: 'background_removal', label: 'Background Removal' },
  { value: 'video_generation', label: 'Video Generation' },
  { value: 'video_upscaling', label: 'Video Upscaling' },
  { value: 'subtitle_processor', label: 'Subtitles' },
  { value: 'text_to_speech', label: 'Text to Speech' },
  { value: 'voice_to_text', label: 'Voice to Text' },
  { value: 'alt_text_generator', label: 'Alt Text' },
  { value: 'prompt_studio', label: 'Prompt Studio' },
];

const statusFilters = [
  { value: '', label: 'All Status' },
  { value: 'completed', label: 'Completed' },
  { value: 'processing', label: 'Processing' },
  { value: 'pending', label: 'Pending' },
  { value: 'failed', label: 'Failed' },
];

export default function HistoryPage() {
  const [jobs, setJobs] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [moduleFilter, setModuleFilter] = useState('');
  const [statusFilter, setStatusFilter] = useState('');
  const [searchQuery, setSearchQuery] = useState('');
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [selectedJob, setSelectedJob] = useState<any>(null);

  const fetchJobs = async () => {
    setLoading(true);
    try {
      const params: any = {
        page,
        limit: 20,
      };
      if (moduleFilter) params.module = moduleFilter;
      if (statusFilter) params.status = statusFilter;

      const response = await jobsApi.list(params);
      setJobs(response.data.items || []);
      setTotalPages(Math.ceil((response.data.total || 0) / 20));
    } catch (err) {
      toast.error('Failed to load history');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchJobs();
  }, [page, moduleFilter, statusFilter]);

  const handleDownload = async (assetId: string, filename: string) => {
    try {
      const response = await assetsApi.download(assetId);
      const url = window.URL.createObjectURL(response.data);
      const a = document.createElement('a');
      a.href = url;
      a.download = filename;
      a.click();
      window.URL.revokeObjectURL(url);
    } catch (err) {
      toast.error('Failed to download');
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'completed':
        return 'bg-green-900/50 text-green-400';
      case 'processing':
        return 'bg-blue-900/50 text-blue-400';
      case 'pending':
        return 'bg-gray-700 text-gray-300';
      case 'failed':
        return 'bg-red-900/50 text-red-400';
      default:
        return 'bg-gray-700 text-gray-300';
    }
  };

  const formatModuleName = (module: string) => {
    return module?.replace(/_/g, ' ').replace(/\b\w/g, (l) => l.toUpperCase()) || '-';
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <div className="w-12 h-12 bg-forge-yellow/10 rounded-lg flex items-center justify-center">
            <History className="w-6 h-6 text-forge-yellow" />
          </div>
          <div>
            <h1 className="text-2xl font-bold text-white">Work History</h1>
            <p className="text-gray-500">View and manage your past jobs</p>
          </div>
        </div>
      </div>

      {/* Filters */}
      <div className="flex flex-wrap gap-4">
        <div className="flex-1 min-w-[200px]">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-500" />
            <input
              type="text"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              placeholder="Search jobs..."
              className="input-field pl-10"
            />
          </div>
        </div>
        <select
          value={moduleFilter}
          onChange={(e) => {
            setModuleFilter(e.target.value);
            setPage(1);
          }}
          className="select-field w-48"
        >
          {moduleFilters.map((filter) => (
            <option key={filter.value} value={filter.value}>
              {filter.label}
            </option>
          ))}
        </select>
        <select
          value={statusFilter}
          onChange={(e) => {
            setStatusFilter(e.target.value);
            setPage(1);
          }}
          className="select-field w-40"
        >
          {statusFilters.map((filter) => (
            <option key={filter.value} value={filter.value}>
              {filter.label}
            </option>
          ))}
        </select>
      </div>

      {/* Jobs Table */}
      <div className="bg-forge-dark rounded-xl border border-gray-800 overflow-hidden">
        {loading ? (
          <div className="p-8 text-center text-gray-500">Loading...</div>
        ) : jobs.length === 0 ? (
          <div className="p-8 text-center text-gray-500">No jobs found</div>
        ) : (
          <table className="w-full">
            <thead>
              <tr className="border-b border-gray-800">
                <th className="text-left px-6 py-4 text-sm font-medium text-gray-500">
                  Module
                </th>
                <th className="text-left px-6 py-4 text-sm font-medium text-gray-500">
                  Status
                </th>
                <th className="text-left px-6 py-4 text-sm font-medium text-gray-500">
                  Provider
                </th>
                <th className="text-left px-6 py-4 text-sm font-medium text-gray-500">
                  Created
                </th>
                <th className="text-left px-6 py-4 text-sm font-medium text-gray-500">
                  Duration
                </th>
                <th className="text-right px-6 py-4 text-sm font-medium text-gray-500">
                  Actions
                </th>
              </tr>
            </thead>
            <tbody>
              {jobs.map((job) => (
                <tr
                  key={job.id}
                  className="border-b border-gray-800 last:border-0 hover:bg-forge-gray/50"
                >
                  <td className="px-6 py-4">
                    <span className="text-white font-medium">
                      {formatModuleName(job.module)}
                    </span>
                  </td>
                  <td className="px-6 py-4">
                    <span className={`badge ${getStatusColor(job.status)}`}>
                      {job.status}
                    </span>
                  </td>
                  <td className="px-6 py-4 text-gray-400">
                    {job.api_provider || '-'}
                    {job.api_model && (
                      <span className="text-gray-600 text-xs block">
                        {job.api_model}
                      </span>
                    )}
                  </td>
                  <td className="px-6 py-4 text-gray-400 text-sm">
                    {format(new Date(job.created_at), 'MMM d, yyyy HH:mm')}
                  </td>
                  <td className="px-6 py-4 text-gray-400 text-sm">
                    {job.completed_at
                      ? `${Math.round(
                          (new Date(job.completed_at).getTime() -
                            new Date(job.created_at).getTime()) /
                            1000
                        )}s`
                      : '-'}
                  </td>
                  <td className="px-6 py-4">
                    <div className="flex items-center justify-end gap-2">
                      <button
                        onClick={() => setSelectedJob(job)}
                        className="p-2 text-gray-400 hover:text-forge-yellow transition-colors"
                        title="View details"
                      >
                        <Eye className="w-4 h-4" />
                      </button>
                      {job.output_asset_ids?.[0] && (
                        <button
                          onClick={() =>
                            handleDownload(
                              job.output_asset_ids[0],
                              `output_${job.id}`
                            )
                          }
                          className="p-2 text-gray-400 hover:text-forge-yellow transition-colors"
                          title="Download"
                        >
                          <Download className="w-4 h-4" />
                        </button>
                      )}
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>

      {/* Pagination */}
      {totalPages > 1 && (
        <div className="flex items-center justify-center gap-2">
          <button
            onClick={() => setPage((p) => Math.max(1, p - 1))}
            disabled={page === 1}
            className="btn-secondary px-4 py-2 disabled:opacity-50"
          >
            Previous
          </button>
          <span className="text-gray-400 px-4">
            Page {page} of {totalPages}
          </span>
          <button
            onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
            disabled={page === totalPages}
            className="btn-secondary px-4 py-2 disabled:opacity-50"
          >
            Next
          </button>
        </div>
      )}

      {/* Job Detail Modal */}
      {selectedJob && (
        <div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50 p-4">
          <div className="bg-forge-dark rounded-xl border border-gray-800 max-w-2xl w-full max-h-[80vh] overflow-y-auto">
            <div className="p-6 border-b border-gray-800 flex items-center justify-between">
              <h3 className="text-lg font-semibold text-white">Job Details</h3>
              <button
                onClick={() => setSelectedJob(null)}
                className="text-gray-400 hover:text-white"
              >
                &times;
              </button>
            </div>
            <div className="p-6 space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <p className="text-sm text-gray-500">Job ID</p>
                  <p className="text-white font-mono text-sm">{selectedJob.id}</p>
                </div>
                <div>
                  <p className="text-sm text-gray-500">Module</p>
                  <p className="text-white">{formatModuleName(selectedJob.module)}</p>
                </div>
                <div>
                  <p className="text-sm text-gray-500">Status</p>
                  <span className={`badge ${getStatusColor(selectedJob.status)}`}>
                    {selectedJob.status}
                  </span>
                </div>
                <div>
                  <p className="text-sm text-gray-500">Progress</p>
                  <p className="text-white">{selectedJob.progress}%</p>
                </div>
                <div>
                  <p className="text-sm text-gray-500">Provider</p>
                  <p className="text-white">{selectedJob.api_provider || '-'}</p>
                </div>
                <div>
                  <p className="text-sm text-gray-500">Model</p>
                  <p className="text-white">{selectedJob.api_model || '-'}</p>
                </div>
              </div>

              {selectedJob.error_message && (
                <div className="bg-red-900/20 border border-red-800 rounded-lg p-4">
                  <p className="text-sm text-red-400">{selectedJob.error_message}</p>
                </div>
              )}

              {selectedJob.input_data && (
                <div>
                  <p className="text-sm text-gray-500 mb-2">Input Data</p>
                  <pre className="bg-forge-gray rounded-lg p-4 text-sm text-gray-300 overflow-x-auto">
                    {JSON.stringify(selectedJob.input_data, null, 2)}
                  </pre>
                </div>
              )}

              {selectedJob.output_data && (
                <div>
                  <p className="text-sm text-gray-500 mb-2">Output Data</p>
                  <pre className="bg-forge-gray rounded-lg p-4 text-sm text-gray-300 overflow-x-auto">
                    {JSON.stringify(selectedJob.output_data, null, 2)}
                  </pre>
                </div>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
