import React, { useState } from 'react';
import { useForm, useFieldArray } from 'react-hook-form';
import { useNavigate } from 'react-router-dom';
import { toast } from 'react-toastify';
import { Container, Row, Col, Form, Button, Card } from 'react-bootstrap';
import '../../CSS/CSS/CommonStyle.css';
import { addReport, getKeysFromUrl } from '../../../../APIServices/reportBaseUrlAddAPI';

const ReportBuild2Add = () => {
  const { register, handleSubmit, control, formState: { errors } } = useForm({
    defaultValues: {
      reportName: '',
      description: '',
      active: false,
      isSql: false,
      Rpt_builder2_lines: [{ model: '' }],
    },
  });

  const { fields, append } = useFieldArray({
    control,
    name: 'Rpt_builder2_lines',
  });

  const [keysFromUrl, setKeysFromUrl] = useState([]);
  const navigate = useNavigate();

  const handleGetKeys = async (url) => {
    if (!url) {
      toast.error('URL is required');
      return;
    }
    try {
      const data = await getKeysFromUrl(url);
      setKeysFromUrl(data);
      toast.success('Keys retrieved successfully');
    } catch (error) {
      toast.error(error || 'Failed to retrieve keys');
    }
  };

  // const onSubmit = async (formData) => {
  //   try {
  //     const { status } = await addReport(formData);
  //     if (status >= 200 && status <= 209) {
  //       toast.success('Report saved successfully');
  //       navigate('/admin/reportbuild2all');
  //     } else {
  //       toast.error('Report save unsuccessful');
  //     }
  //   } catch (error) {
  //     toast.error(error || 'Error saving report');
  //   }
  // };
  const onSubmit = async (formData) => {
    // Prepare the formData to match the backend API requirements
    const updatedData = {
      reportName: formData.reportName, // Use the correct field name
      description: formData.description,
      active: formData.active || false, // Ensure `active` is passed and defaults to `false`
      isSql: formData.isSql || false,   // Ensure `isSql` is passed and defaults to `false`
      Rpt_builder2_lines: formData.Rpt_builder2_lines || [] // Default to empty array if not provided
    };
    
  
    try {
      const { status } = await addReport(updatedData);
      console.log("Report added successfully...")
      if (status >= 200 && status <= 209) {
        toast.success('Report saved successfully');
        console.log('Report Saved successfully...')
        navigate('/admin/reportbuild2all');
      } else {
        toast.error('Report save unsuccessful');
      }
    } catch (error) {
      toast.error(error || 'Error saving report');
    }
  };
  
  const handleCancel = () => {
    navigate('/admin/reportbuild2all');
  };

  return (
    <Container>
      <Card className="shadow-sm mb-4">
        <Card.Header className="d-flex justify-content-between align-items-center">
          <h4 className="m-0" style={{ fontWeight: 400, color: '#0E6591' }}>
            <b>Create New Report</b>
          </h4>
          <span className="badge bg-info">Add Mode</span>
        </Card.Header>
        <Card.Body>
          <Form onSubmit={handleSubmit(onSubmit)}>
            <Row className="mb-3">
              <Col md={4} sm={12}>
                <Form.Group controlId="reportName">
                  <Form.Label>Report Name</Form.Label>
                  <Form.Control
                    type="text"
                    placeholder="Enter name"
                    {...register('reportName', { required: 'Report name is required' })}
                    isInvalid={errors.reportName}
                    className="custom-hover-border"
                  />
                  <Form.Control.Feedback type="invalid">
                    {errors.reportName?.message}
                  </Form.Control.Feedback>
                </Form.Group>
              </Col>
              <Col md={4} sm={12}>
                <Form.Group controlId="description">
                  <Form.Label>Description</Form.Label>
                  <Form.Control
                    as="textarea"
                    rows={2}
                    placeholder="Enter Description"
                    {...register('description')}
                    className="custom-hover-border"
                  />
                </Form.Group>
              </Col>
              <Col md={4} sm={12}>
                <Form.Group controlId="active">
                  <Form.Label>Active</Form.Label>
                  <Form.Check type="checkbox" label="Active" {...register('active')} />
                </Form.Group>
              </Col>
            </Row>

            <Row>
              {fields.map((item, index) => (
                <Col key={item.id} md={4} sm={12}>
                  {/* <Form.Group controlId={`Rpt_builder2_lines.${index}.model`}>
                    <Form.Label>Model</Form.Label>
                    <Form.Control
                      type="text"
                      placeholder="Enter model"
                      {...register(`Rpt_builder2_lines.${index}.model`)}
                      className="custom-hover-border"
                    />
                  </Form.Group> */}
                </Col>
              ))}
              <Col md={12} className="d-flex justify-content-start mt-3">
                {/* <Button
                  variant="outline"
                  onClick={() => append({ model: '' })}
                  className="custom_manage_column_button"
                >
                  Add Line
                </Button> */}
              </Col>
            </Row>

            <Row className="mt-4">
              <Col className="d-flex justify-content-center">
                <div className="btn-group">
                  <Button variant="secondary" onClick={handleCancel}>
                    Cancel
                  </Button>
                  <Button variant="primary" type="submit" className="ms-2 custom_button" onClick={onSubmit}>
                    Submit
                  </Button>
                </div>
              </Col>
            </Row>
          </Form>
        </Card.Body>
      </Card>
    </Container>
  );
};

export default ReportBuild2Add;
