import * as React from 'react';
import { useTranslation } from 'react-i18next';
import {
  Button,
  Card,
  CardBody,
  CardHeader,
  CardTitle,
  Spinner,
  Text,
  TextContent,
} from '@patternfly/react-core';
import { CheckCircleIcon, PauseIcon, PlayIcon } from '@patternfly/react-icons';
import './project-pause-card.css';

type ProjectState = {
  isPaused: boolean;
  pausedSince?: string;
  isLoading: boolean;
  error?: string;
};

type ProjectPauseCardProps = {
  projectName?: string;
};

export default function ProjectPauseCard({ projectName }: ProjectPauseCardProps) {
  const { t } = useTranslation('plugin__project-pause-plugin');
  const [projectState, setProjectState] = React.useState<ProjectState>({
    isPaused: false,
    isLoading: true,
  });

  // Fetch initial state
  React.useEffect(() => {
    if (projectName) {
      fetchProjectState();
    }
  }, [projectName]);

  const fetchProjectState = async () => {
    try {
      // TODO: Replace with actual API endpoint
      const response = await fetch(`/api/proxy/project-pause-operator/v1/namespaces/${projectName}/state`);
      const data = await response.json();
      setProjectState({
        isPaused: data.isPaused,
        pausedSince: data.pausedSince,
        isLoading: false,
      });
    } catch (error) {
      console.error('Failed to fetch project state:', error);
      setProjectState(prev => ({
        ...prev,
        isLoading: false,
        error: 'Failed to fetch project state',
      }));
    }
  };

  const handlePauseProject = React.useCallback(async () => {
    setProjectState(prev => ({ ...prev, isLoading: true }));
    try {
      // TODO: Replace with actual API endpoint
      const response = await fetch(`/api/proxy/project-pause-operator/v1/namespaces/${projectName}/toggle`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          pause: !projectState.isPaused,
        }),
      });
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      
      // Refresh the state after toggling
      await fetchProjectState();
    } catch (error) {
      console.error('Failed to toggle project state:', error);
      setProjectState(prev => ({
        ...prev,
        isLoading: false,
        error: 'Failed to toggle project state',
      }));
    }
  }, [projectName, projectState.isPaused]);

  const formatTimestamp = (timestamp: string) => {
    return new Date(timestamp).toLocaleString();
  };

  return (
    <div className="project-pause-plugin__inventory-item">
      {projectState.error ? (
        <Text component="p" className="project-pause-plugin__error">
          {projectState.error}
        </Text>
      ) : (
        <>
          <Text component="p" className="project-pause-plugin__controls">
            <Button 
              variant="primary"
              icon={projectState.isPaused ? <PlayIcon /> : <PauseIcon />}
              onClick={handlePauseProject}
              isDisabled={projectState.isLoading}
              size="sm"
            >
              {projectState.isLoading ? (
                <>
                  <Spinner size="sm" /> {t('Processing...')}
                </>
              ) : projectState.isPaused ? (
                t('Resume Project')
              ) : (
                t('Pause Project')
              )}
            </Button>
            <span className="project-pause-plugin__status">
              <CheckCircleIcon /> {projectState.isPaused ? t('Paused') : t('Running')}
            </span>
          </Text>
          {projectState.isPaused && projectState.pausedSince && (
            <Text component="p" className="project-pause-plugin__timestamp">
              {t('Paused since:')} {formatTimestamp(projectState.pausedSince)}
            </Text>
          )}
        </>
      )}
    </div>
  );
} 