'use client';

import { useState } from 'react';
import { useProcesses, useProcessLogs, useMainLog, useClearProcessLogs, useClearMainLog } from '@/lib/hooks/useSupervisor';
import { LogViewer } from '@/components/logs/LogViewer';
import { LogControls } from '@/components/logs/LogControls';
import { LogSearch } from '@/components/logs/LogSearch';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { AlertCircle } from 'lucide-react';

export default function LogsPage() {
  const [selectedProcess, setSelectedProcess] = useState<string | 'main'>('main');
  const [logType, setLogType] = useState<'stdout' | 'stderr'>('stdout');
  const [searchTerm, setSearchTerm] = useState('');
  const [isPlaying, setIsPlaying] = useState(true);
  const [autoScroll, setAutoScroll] = useState(true);

  const { data: processes, isError: processesError } = useProcesses({
    refetchInterval: isPlaying ? 3000 : undefined,
  });

  // Fetch logs based on selection
  const { data: processLogs, isLoading: processLogsLoading, refetch: refetchProcessLogs } = useProcessLogs(
    selectedProcess as string,
    logType,
    {
      enabled: selectedProcess !== 'main' && isPlaying,
      refetchInterval: isPlaying ? 2000 : undefined,
    }
  );

  const { data: mainLogData, isLoading: mainLogLoading, refetch: refetchMainLog } = useMainLog({
    enabled: selectedProcess === 'main' && isPlaying,
    refetchInterval: isPlaying ? 2000 : undefined,
  });

  const clearProcessLogsMutation = useClearProcessLogs();
  const clearMainLogMutation = useClearMainLog();

  const currentLogs = selectedProcess === 'main'
    ? mainLogData?.logs || ''
    : processLogs?.bytes || '';

  const isLoading = selectedProcess === 'main' ? mainLogLoading : processLogsLoading;

  const handleRefresh = () => {
    if (selectedProcess === 'main') {
      refetchMainLog();
    } else {
      refetchProcessLogs();
    }
  };

  const handleClear = () => {
    if (!confirm('Are you sure you want to clear these logs?')) return;

    if (selectedProcess === 'main') {
      clearMainLogMutation.mutate();
    } else {
      clearProcessLogsMutation.mutate(selectedProcess);
    }
  };

  const handleDownload = () => {
    const blob = new Blob([currentLogs], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `${selectedProcess === 'main' ? 'supervisord' : selectedProcess}-${logType}-${Date.now()}.log`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  };

  if (processesError) {
    return (
      <div className="space-y-4 md:space-y-6">
        <h1 className="text-2xl sm:text-3xl font-bold">Process Logs</h1>
        <Card className="border-destructive/50">
          <CardContent className="p-8 md:p-12 text-center">
            <AlertCircle className="h-10 w-10 md:h-12 md:w-12 text-destructive mx-auto mb-4" />
            <h2 className="text-lg md:text-xl font-semibold mb-2">Failed to load processes</h2>
            <p className="text-sm md:text-base text-muted-foreground">
              Could not connect to Supervisor. Please check your configuration.
            </p>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="space-y-4 md:space-y-6 h-[calc(100vh-10rem)] md:h-[calc(100vh-12rem)] flex flex-col">
      <div className="flex-shrink-0">
        <h1 className="text-2xl sm:text-3xl font-bold">Process Logs</h1>
        <p className="text-sm md:text-base text-muted-foreground mt-1">Real-time log viewing and management</p>
      </div>

      {/* Controls */}
      <Card className="flex-shrink-0">
        <CardHeader className="pb-3 md:pb-4">
          <CardTitle className="text-base md:text-lg">Log Controls</CardTitle>
        </CardHeader>
        <CardContent className="space-y-3 md:space-y-4">
          {/* Process Selector */}
          <div className="flex flex-col sm:flex-row gap-3 sm:gap-4">
            <div className="flex-1 min-w-[200px]">
              <label className="block text-sm font-medium mb-2">Select Process</label>
              <select
                value={selectedProcess}
                onChange={(e) => setSelectedProcess(e.target.value)}
                className="w-full h-10 rounded-md border border-input bg-background px-3 py-2 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
              >
                <option value="main">Supervisord (Main Log)</option>
                {processes?.map((proc) => (
                  <option key={`${proc.group}:${proc.name}`} value={`${proc.group}:${proc.name}`}>
                    {proc.group}:{proc.name}
                  </option>
                ))}
              </select>
            </div>

            {/* Log Type Selector (only for processes, not main) */}
            {selectedProcess !== 'main' && (
              <div>
                <label className="block text-sm font-medium mb-2">Log Type</label>
                <div className="flex gap-2">
                  <Button
                    variant={logType === 'stdout' ? 'default' : 'outline'}
                    size="sm"
                    onClick={() => setLogType('stdout')}
                    className="flex-1 sm:flex-initial"
                  >
                    Stdout
                  </Button>
                  <Button
                    variant={logType === 'stderr' ? 'default' : 'outline'}
                    size="sm"
                    onClick={() => setLogType('stderr')}
                    className="flex-1 sm:flex-initial"
                  >
                    Stderr
                  </Button>
                </div>
              </div>
            )}
          </div>

          {/* Search and Controls */}
          <div className="flex flex-col sm:flex-row flex-wrap gap-3 sm:gap-4 items-stretch sm:items-end">
            <LogSearch value={searchTerm} onChange={setSearchTerm} />
            <LogControls
              isPlaying={isPlaying}
              onPlayPause={() => setIsPlaying(!isPlaying)}
              autoScroll={autoScroll}
              onToggleAutoScroll={() => setAutoScroll(!autoScroll)}
              onRefresh={handleRefresh}
              onClear={handleClear}
              onDownload={handleDownload}
              isClearing={clearProcessLogsMutation.isPending || clearMainLogMutation.isPending}
            />
          </div>
        </CardContent>
      </Card>

      {/* Log Viewer */}
      <div className="flex-1 min-h-0">
        <LogViewer
          logs={currentLogs}
          isLoading={isLoading}
          autoScroll={autoScroll}
          searchTerm={searchTerm}
        />
      </div>
    </div>
  );
}
