'use client';

import { useState, useEffect, useCallback } from 'react';
import { Timer, Play, MoreHorizontal, RefreshCw } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { createProxyFetch } from '@/lib/proxy-fetch';

interface Job {
  id: string;
  name: string;
  schedule: string;
  description?: string;
  enabled: boolean;
  lastRunAt?: string;
  lastRunStatus?: string;
  nextRunAt?: string;
}

interface Run {
  id: string;
  jobId: string;
  jobName?: string;
  status: string;
  duration?: number;
  error?: string;
  startedAt: string;
  completedAt?: string;
}

const statusConfig: Record<string, { color: string }> = {
  success: { color: 'bg-emerald-50 text-emerald-700' },
  failed: { color: 'bg-red-50 text-red-700' },
  running: { color: 'bg-blue-50 text-blue-700' },
  skipped: { color: 'bg-gray-50 text-gray-600' },
};

function formatDate(iso: string) {
  return new Date(iso).toLocaleString('en-US', {
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  });
}

const jobsFetch = createProxyFetch('/api/jobs');
const runsFetch = createProxyFetch('/api/runs');

export default function JobsPage() {
  const [jobs, setJobs] = useState<Job[]>([]);
  const [runs, setRuns] = useState<Run[]>([]);
  const [loading, setLoading] = useState(true);
  const [tab, setTab] = useState<'jobs' | 'runs'>('jobs');

  const loadData = useCallback(async () => {
    setLoading(true);
    const [jData, rData] = await Promise.all([jobsFetch(''), runsFetch('?limit=50')]);
    setJobs(Array.isArray(jData?.jobs) ? jData.jobs : Array.isArray(jData) ? jData : []);
    setRuns(Array.isArray(rData?.runs) ? rData.runs : Array.isArray(rData) ? rData : []);
    setLoading(false);
  }, []);

  useEffect(() => {
    void loadData();
  }, [loadData]);

  async function handleTrigger(id: string) {
    await jobsFetch('trigger', { method: 'POST', body: JSON.stringify({ jobId: id }) });
    loadData();
  }

  async function handleToggle(job: Job) {
    await jobsFetch(`${job.id}`, {
      method: 'PUT',
      body: JSON.stringify({ enabled: !job.enabled }),
    });
    loadData();
  }

  const enabledCount = jobs.filter(j => j.enabled).length;
  const recentFailures = runs.filter(r => r.status === 'failed').length;

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">Scheduled Jobs</h1>
          <p className="text-sm text-muted-foreground">
            View registered jobs, trigger runs, and inspect execution history
          </p>
        </div>
        <Button variant="outline" onClick={loadData}>
          <RefreshCw className="mr-2 h-4 w-4" /> Refresh
        </Button>
      </div>

      <div className="grid gap-4 md:grid-cols-4">
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">Total Jobs</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{jobs.length}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">Enabled</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-emerald-600">{enabledCount}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">Recent Runs</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{runs.length}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">Failures</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-red-600">{recentFailures}</div>
          </CardContent>
        </Card>
      </div>

      <div className="flex gap-2">
        <Button
          variant={tab === 'jobs' ? 'default' : 'outline'}
          size="sm"
          onClick={() => setTab('jobs')}
        >
          Jobs ({jobs.length})
        </Button>
        <Button
          variant={tab === 'runs' ? 'default' : 'outline'}
          size="sm"
          onClick={() => setTab('runs')}
        >
          Runs ({runs.length})
        </Button>
      </div>

      {tab === 'jobs' && (
        <Card>
          <CardContent className="p-0">
            {loading ? (
              <div className="p-8 text-center text-muted-foreground">Loading...</div>
            ) : jobs.length === 0 ? (
              <div className="p-8 text-center text-muted-foreground">
                <Timer className="mx-auto mb-2 h-8 w-8 opacity-40" />
                No scheduled jobs registered.
              </div>
            ) : (
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Job</TableHead>
                    <TableHead>Schedule</TableHead>
                    <TableHead>Enabled</TableHead>
                    <TableHead>Last Run</TableHead>
                    <TableHead>Next Run</TableHead>
                    <TableHead className="w-[50px]" />
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {jobs.map(j => (
                    <TableRow key={j.id}>
                      <TableCell>
                        <div className="font-medium">{j.name}</div>
                        {j.description && (
                          <p className="text-xs text-muted-foreground">{j.description}</p>
                        )}
                      </TableCell>
                      <TableCell>
                        <code className="text-xs bg-muted px-1.5 py-0.5 rounded">{j.schedule}</code>
                      </TableCell>
                      <TableCell>
                        <Badge
                          className={
                            j.enabled
                              ? 'bg-emerald-50 text-emerald-700 border-0'
                              : 'bg-gray-50 text-gray-600 border-0'
                          }
                        >
                          {j.enabled ? 'Enabled' : 'Disabled'}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        {j.lastRunAt ? (
                          <div>
                            <span className="text-xs text-muted-foreground">
                              {formatDate(j.lastRunAt)}
                            </span>
                            {j.lastRunStatus && (
                              <Badge
                                className={`ml-2 text-xs ${(statusConfig[j.lastRunStatus] || statusConfig.skipped).color} border-0`}
                              >
                                {j.lastRunStatus}
                              </Badge>
                            )}
                          </div>
                        ) : (
                          <span className="text-xs text-muted-foreground">Never</span>
                        )}
                      </TableCell>
                      <TableCell className="text-xs text-muted-foreground">
                        {j.nextRunAt ? formatDate(j.nextRunAt) : '—'}
                      </TableCell>
                      <TableCell>
                        <DropdownMenu>
                          <DropdownMenuTrigger asChild>
                            <Button variant="ghost" size="icon" className="h-8 w-8">
                              <MoreHorizontal className="h-4 w-4" />
                            </Button>
                          </DropdownMenuTrigger>
                          <DropdownMenuContent align="end">
                            <DropdownMenuItem onClick={() => handleTrigger(j.id)}>
                              <Play className="mr-2 h-4 w-4" />
                              Trigger Now
                            </DropdownMenuItem>
                            <DropdownMenuItem onClick={() => handleToggle(j)}>
                              {j.enabled ? 'Disable' : 'Enable'}
                            </DropdownMenuItem>
                          </DropdownMenuContent>
                        </DropdownMenu>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            )}
          </CardContent>
        </Card>
      )}

      {tab === 'runs' && (
        <Card>
          <CardContent className="p-0">
            {runs.length === 0 ? (
              <div className="p-8 text-center text-muted-foreground">No job runs yet.</div>
            ) : (
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Job</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead>Duration</TableHead>
                    <TableHead>Started</TableHead>
                    <TableHead>Error</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {runs.map(r => {
                    const cfg = statusConfig[r.status] || statusConfig.skipped;
                    return (
                      <TableRow key={r.id}>
                        <TableCell className="font-medium text-sm">
                          {r.jobName || r.jobId}
                        </TableCell>
                        <TableCell>
                          <Badge className={`${cfg.color} border-0`}>{r.status}</Badge>
                        </TableCell>
                        <TableCell className="text-xs">
                          {r.duration != null ? `${r.duration}ms` : '—'}
                        </TableCell>
                        <TableCell className="text-xs text-muted-foreground">
                          {formatDate(r.startedAt)}
                        </TableCell>
                        <TableCell className="text-xs text-red-600 max-w-[200px] truncate">
                          {r.error || '—'}
                        </TableCell>
                      </TableRow>
                    );
                  })}
                </TableBody>
              </Table>
            )}
          </CardContent>
        </Card>
      )}
    </div>
  );
}
