import { useState, useEffect } from 'react';
import { getNamespaces, getPVCs, createBackup } from '../service';
import '../style/BackupForm.css';
import { Button, Input, Select, Option } from '@mui/base';

function BackupForm() {
  const [namespaces, setNamespaces] = useState([]);
  const [pvcs, setPvcs] = useState([]);
  const [namespace, setNamespace] = useState('');
  const [pvc, setPvc] = useState('');
  const [backupName, setBackupName] = useState('');

  useEffect(() => {
    getNamespaces().then(setNamespaces);
  }, []);

  useEffect(() => {
    if (namespace) {
      getPVCs(namespace).then(setPvcs);
    } else {
      setPvcs([]);
    }
  }, [namespace]);

  const handleSubmit = async () => {
    try {
      await createBackup({ namespace, pvcName: pvc, backupName });
      alert('✅ Backup created successfully!');
    } catch (error) {
      console.error(error);
      alert('❌ Backup failed');
    }
  };

  return (
    <div className="form-container BackupForm">
      <h3>📦 Create Backup</h3>
      <div className="form-group">
        <label>Namespace</label>
        <Select value={namespace} onChange={(e) => setNamespace(e.target.value)}>
          <Option value="">-- Select Namespace --</Option>
          {namespaces.map((ns) => (
            <Option key={ns} value={ns}>{ns}</Option>
          ))}
        </Select>
      </div>

      <div className="form-group">
        <label>PVC</label>
        <Select value={pvc} onChange={(e) => setPvc(e.target.value)} disabled={!namespace}>
          <Option value="">-- Select PVC --</Option>
          {pvcs.map((p) => (
            <Option key={p} value={p}>{p}</Option>
          ))}
        </Select>
      </div>

      <div className="form-group">
        <label>Backup Name</label>
        <Input
          type="text"
          value={backupName}
          onChange={(e) => setBackupName(e.target.value)}
        />
      </div>

      <Button className="btn" onClick={handleSubmit} disabled={!namespace || !pvc || !backupName}>
        Create Backup
      </Button>
    </div>
  );
}

export default BackupForm;
