import React, { useState, useCallback } from 'react';
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Label } from "@/components/ui/label";

const LoadTester = ({
  contextPath = '/',
  scenarios = [],
  test,
  onTestUpdate
}) => {
  const [isLoading, setIsLoading] = useState(false);

  // Handler for starting the load test
  const handleStartTest = useCallback(async () => {
    if (!test?.scenarioId) {
      alert('Please select a scenario');
      return;
    }

    setIsLoading(true);
    try {
      const response = await fetch(`${contextPath}startLoadTest`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-XSRF-TOKEN': document.querySelector('meta[name="_csrf"]')?.getAttribute('content')
        },
        body: JSON.stringify(test)
      });

      if (!response.ok) {
        throw new Error('Failed to start test');
      }
    } catch (error) {
      console.error('Error starting test:', error);
      alert(error.message);
    } finally {
      setIsLoading(false);
    }
  }, [test, contextPath]);

  // Handler for stopping the load test
  const handleStopTest = useCallback(async () => {
    setIsLoading(true);
    try {
      const response = await fetch(`${contextPath}stopLoadTest`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-XSRF-TOKEN': document.querySelector('meta[name="_csrf"]')?.getAttribute('content')
        },
        body: JSON.stringify(test)
      });

      if (!response.ok) {
        throw new Error('Failed to stop test');
      }
    } catch (error) {
      console.error('Error stopping test:', error);
      alert(error.message);
    } finally {
      setIsLoading(false);
    }
  }, [test, contextPath]);

  // Handler for input changes
  const handleChange = useCallback((field, value) => {
    onTestUpdate({
      ...test,
      [field]: value
    });
  }, [test, onTestUpdate]);

  if (!test) return null;

  return (
      <Card>
        <CardHeader>Load Test Configuration</CardHeader>
        <CardContent>
          <div className="grid gap-4">
            {/* Scenario Selection */}
            <div className="space-y-2">
              <Label>Scenario</Label>
              <Select
                  value={test.scenarioId || ''}
                  onValueChange={(value) => handleChange('scenarioId', value)}
                  disabled={isLoading}
              >
                <SelectTrigger>
                  <SelectValue placeholder="Select scenario" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="">Select scenario</SelectItem>
                  {scenarios.map((scenario) => (
                      <SelectItem key={scenario.id} value={scenario.id}>
                        {scenario.name}
                      </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            {/* Thread Count */}
            <div className="space-y-2">
              <Label>Thread Count</Label>
              <Input
                  type="number"
                  min="1"
                  value={test.threadCount || 1}
                  onChange={(e) => handleChange('threadCount', parseInt(e.target.value))}
                  disabled={isLoading}
              />
            </div>

            {/* Loop Count */}
            <div className="space-y-2">
              <Label>Loop Count</Label>
              <Input
                  type="number"
                  min="0"
                  value={test.loopCount || 0}
                  onChange={(e) => handleChange('loopCount', parseInt(e.target.value))}
                  disabled={isLoading}
              />
            </div>

            {/* Ramp Up Time */}
            <div className="space-y-2">
              <Label>Ramp-up Time (ms)</Label>
              <Input
                  type="number"
                  min="0"
                  value={test.rampUpTime || 0}
                  onChange={(e) => handleChange('rampUpTime', parseInt(e.target.value))}
                  disabled={isLoading}
              />
            </div>

            {/* Duration */}
            <div className="space-y-2">
              <Label>Duration (minutes)</Label>
              <Input
                  type="number"
                  min="0"
                  value={test.duration || 0}
                  onChange={(e) => handleChange('duration', parseInt(e.target.value))}
                  disabled={isLoading}
              />
            </div>

            {/* Control Buttons */}
            <div className="flex gap-2 pt-4">
              <Button
                  onClick={handleStartTest}
                  disabled={isLoading}
              >
                Start Test
              </Button>
              <Button
                  onClick={handleStopTest}
                  disabled={isLoading}
                  variant="secondary"
              >
                Stop Test
              </Button>
            </div>
          </div>
        </CardContent>
      </Card>
  );
};

export default LoadTester;
