'use client';

import { useState } from 'react';
import { useSignalProcess } from '@/lib/hooks/useSupervisor';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { X, AlertTriangle } from 'lucide-react';
import { cn } from '@/lib/utils/cn';

interface SignalSenderProps {
  processName: string;
  onClose: () => void;
}

const COMMON_SIGNALS = [
  { value: 'HUP', label: 'HUP (1)', description: 'Hangup - reload configuration', dangerous: false },
  { value: 'INT', label: 'INT (2)', description: 'Interrupt - graceful shutdown', dangerous: false },
  { value: 'QUIT', label: 'QUIT (3)', description: 'Quit', dangerous: false },
  { value: 'TERM', label: 'TERM (15)', description: 'Terminate - graceful shutdown', dangerous: true },
  { value: 'KILL', label: 'KILL (9)', description: 'Kill - immediate termination', dangerous: true },
  { value: 'USR1', label: 'USR1 (10)', description: 'User-defined signal 1', dangerous: false },
  { value: 'USR2', label: 'USR2 (12)', description: 'User-defined signal 2', dangerous: false },
];

export function SignalSender({ processName, onClose }: SignalSenderProps) {
  const [selectedSignal, setSelectedSignal] = useState<string>('');
  const [customSignal, setCustomSignal] = useState('');
  const [showConfirm, setShowConfirm] = useState(false);

  const signalMutation = useSignalProcess();

  const handleSendSignal = () => {
    const signal = selectedSignal || customSignal;
    if (!signal) return;

    const isDangerous = ['TERM', 'KILL', 'QUIT'].includes(signal.toUpperCase());

    if (isDangerous && !showConfirm) {
      setShowConfirm(true);
      return;
    }

    signalMutation.mutate(
      { name: processName, signal },
      {
        onSuccess: () => {
          onClose();
        },
      }
    );
  };

  const signal = selectedSignal || customSignal;
  const isDangerous = signal && ['TERM', 'KILL', 'QUIT'].includes(signal.toUpperCase());

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm p-4">
      <Card className="w-full max-w-lg shadow-2xl">
        <CardHeader>
          <div className="flex items-center justify-between">
            <div>
              <CardTitle>Send Signal</CardTitle>
              <CardDescription className="mt-1">
                Send Unix signal to <span className="font-mono text-foreground">{processName}</span>
              </CardDescription>
            </div>
            <Button variant="ghost" size="icon" onClick={onClose}>
              <X className="h-4 w-4" />
            </Button>
          </div>
        </CardHeader>

        <CardContent className="space-y-6">
          {/* Common Signals */}
          <div>
            <label className="text-sm font-medium mb-3 block">Common Signals</label>
            <div className="grid grid-cols-2 gap-2">
              {COMMON_SIGNALS.map((sig) => (
                <Button
                  key={sig.value}
                  variant={selectedSignal === sig.value ? 'default' : 'outline'}
                  className={cn(
                    'justify-start text-left h-auto py-3',
                    sig.dangerous && selectedSignal === sig.value && 'bg-destructive hover:bg-destructive/90'
                  )}
                  onClick={() => {
                    setSelectedSignal(sig.value);
                    setCustomSignal('');
                    setShowConfirm(false);
                  }}
                >
                  <div>
                    <div className="font-semibold">{sig.label}</div>
                    <div className="text-xs opacity-80">{sig.description}</div>
                  </div>
                </Button>
              ))}
            </div>
          </div>

          {/* Custom Signal */}
          <div>
            <label className="text-sm font-medium mb-2 block">Custom Signal</label>
            <input
              type="text"
              placeholder="e.g., WINCH, CONT, STOP"
              value={customSignal}
              onChange={(e) => {
                setCustomSignal(e.target.value.toUpperCase());
                setSelectedSignal('');
                setShowConfirm(false);
              }}
              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"
            />
          </div>

          {/* Confirmation Warning */}
          {isDangerous && showConfirm && (
            <div className="p-4 rounded-md bg-destructive/10 border border-destructive/20">
              <div className="flex gap-3">
                <AlertTriangle className="h-5 w-5 text-destructive flex-shrink-0 mt-0.5" />
                <div className="space-y-2">
                  <p className="text-sm font-medium text-destructive">Warning: Dangerous Signal</p>
                  <p className="text-sm text-muted-foreground">
                    Signal <span className="font-mono font-bold">{signal}</span> may terminate or kill the process.
                    Are you sure you want to continue?
                  </p>
                </div>
              </div>
            </div>
          )}

          {/* Actions */}
          <div className="flex gap-2 justify-end">
            <Button variant="outline" onClick={onClose} disabled={signalMutation.isPending}>
              Cancel
            </Button>
            <Button
              onClick={handleSendSignal}
              disabled={!signal || signalMutation.isPending}
              variant={isDangerous && showConfirm ? 'destructive' : 'default'}
            >
              {signalMutation.isPending
                ? 'Sending...'
                : isDangerous && !showConfirm
                ? 'Confirm & Send'
                : `Send ${signal || 'Signal'}`}
            </Button>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
