import React, {useState, useEffect} from 'react';
import {Button} from '@/components/ui/button';
import {Alert, AlertDescription} from '@/components/ui/alert';
import {Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter} from '@/components/ui/dialog';
import {Input} from '@/components/ui/input';
import LoadTester from './LoadTester';
import LoadTestResult from './LoadTestResult';

const LoadTestManager = ({contextPath = '/'}) => {
  const [tests, setTests] = useState([]);
  const [scenarios, setScenarios] = useState([]);
  const [currentTest, setCurrentTest] = useState(null);
  const [loading, setLoading] = useState(false);
  const [toast, setToast] = useState({show: false, message: ''});
  const [newTestDialog, setNewTestDialog] = useState(false);
  const [deleteDialog, setDeleteDialog] = useState({show: false, id: null});
  const [newTestName, setNewTestName] = useState('');

  useEffect(() => {
    loadScenarioList();
    loadTestList();
  }, []);

  const showToast = (message) => {
    setToast({show: true, message});
    setTimeout(() => setToast({show: false, message: ''}), 3000);
  };

  const loadScenarioList = async () => {
    try {
      const response = await fetch(`${contextPath}mgmt/api_scenario/list.do`, {
        headers: {
          'Content-Type': 'application/json',
          'X-XSRF-TOKEN': document.querySelector('meta[name="_csrf"]')?.getAttribute('content')
        }
      });
      const data = await response.json();
      setScenarios(data);
    } catch (error) {
      showToast(error.message);
    }
  };

  const loadTestList = async () => {
    setLoading(true);
    try {
      const response = await fetch(`${contextPath}mgmt/load_test/list.do`, {
        headers: {
          'Content-Type': 'application/json',
          'X-XSRF-TOKEN': document.querySelector('meta[name="_csrf"]')?.getAttribute('content')
        }
      });
      const data = await response.json();
      setTests(data);
    } catch (error) {
      showToast(error.message);
    } finally {
      setLoading(false);
    }
  };

  const handleCreateTest = async () => {
    if (!newTestName) {
      return;
    }

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

      if (!response.ok) {
        throw new Error('Failed to create test');
      }

      await loadTestList();
      setNewTestDialog(false);
      setNewTestName('');
      showToast('Test created successfully');
    } catch (error) {
      showToast(error.message);
    } finally {
      setLoading(false);
    }
  };

  const handleDeleteTest = async () => {
    if (!deleteDialog.id) {
      return;
    }

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

      if (!response.ok) {
        throw new Error('Failed to delete test');
      }

      await loadTestList();
      setDeleteDialog({show: false, id: null});
      showToast('Test deleted successfully');

      if (currentTest?.id === deleteDialog.id) {
        setCurrentTest(null);
      }
    } catch (error) {
      showToast(error.message);
    } finally {
      setLoading(false);
    }
  };

  const handleSaveTest = async () => {
    if (!currentTest) {
      return;
    }

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

      if (!response.ok) {
        throw new Error('Failed to save test');
      }

      showToast('Test saved successfully');
    } catch (error) {
      showToast(error.message);
    } finally {
      setLoading(false);
    }
  };

  return (
      <div className="flex h-full">
        {/* Sidebar */}
        <div className="w-64 border-r p-4 bg-background">
          <div className="space-y-4">
            <Button
                className="w-full"
                onClick={() => setNewTestDialog(true)}
            >
              New Load Test
            </Button>

            <div className="space-y-2">
              {tests.map(test => (
                  <div
                      key={test.id}
                      className={`flex justify-between items-center p-2 rounded hover:bg-accent ${
                          currentTest?.id === test.id ? 'bg-accent' : ''
                      }`}
                  >
                    <button
                        className="flex-1 text-left"
                        onClick={() => setCurrentTest(test)}
                    >
                      {test.name}
                    </button>
                    <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => setDeleteDialog({show: true, id: test.id})}
                    >
                      <i className="fa fa-trash-can"/>
                    </Button>
                  </div>
              ))}
            </div>
          </div>
        </div>

        {/* Main Content */}
        <div className="flex-1 p-4">
          {currentTest ? (
              <div className="space-y-4">
                <div className="flex justify-between items-center">
                  <h2 className="text-2xl font-bold">{currentTest.name}</h2>
                  <div className="space-x-2">
                    <Button onClick={handleSaveTest}>Save</Button>
                    <Button variant="outline" onClick={() => setCurrentTest(null)}>Close</Button>
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div className="border rounded-lg p-4">
                    <LoadTester
                        contextPath={contextPath}
                        scenarios={scenarios}
                        test={currentTest}
                        onTestUpdate={setCurrentTest}
                    />
                  </div>
                  <div className="border rounded-lg p-4">
                    <LoadTestResult
                        contextPath={contextPath}
                        testId={currentTest.id}
                    />
                  </div>
                </div>
              </div>
          ) : (
              <div className="flex items-center justify-center h-full text-muted-foreground">
                Select a test to begin
              </div>
          )}
        </div>

        {/* New Test Dialog */}
        <Dialog open={newTestDialog} onOpenChange={setNewTestDialog}>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>Create New Load Test</DialogTitle>
            </DialogHeader>
            <Input
                value={newTestName}
                onChange={(e) => setNewTestName(e.target.value)}
                placeholder="Test name"
            />
            <DialogFooter>
              <Button variant="outline" onClick={() => setNewTestDialog(false)}>
                Cancel
              </Button>
              <Button onClick={handleCreateTest}>Create</Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>

        {/* Delete Confirmation Dialog */}
        <Dialog
            open={deleteDialog.show}
            onOpenChange={(open) => setDeleteDialog({...deleteDialog, show: open})}
        >
          <DialogContent>
            <DialogHeader>
              <DialogTitle>Delete Test</DialogTitle>
            </DialogHeader>
            <p>Are you sure you want to delete this test?</p>
            <DialogFooter>
              <Button
                  variant="outline"
                  onClick={() => setDeleteDialog({show: false, id: null})}
              >
                Cancel
              </Button>
              <Button
                  variant="destructive"
                  onClick={handleDeleteTest}
              >
                Delete
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>

        {/* Toast */}
        {toast.show && (
            <Alert className="fixed bottom-4 right-4 max-w-md">
              <AlertDescription>{toast.message}</AlertDescription>
            </Alert>
        )}

        {/* Loading Overlay */}
        {loading && (
            <div className="fixed inset-0 bg-background/80 flex items-center justify-center">
              <div className="animate-spin rounded-full h-32 w-32 border-t-2 border-b-2 border-primary"></div>
            </div>
        )}
      </div>
  );
};

export default LoadTestManager;
