import React, { useState, useEffect } from "react";
import ReportBuilderService from "../../../../APIServices/ReportBuilderService";
import { toast } from "react-toastify";
import {
  Container,
  Row,
  Col,
  Form,
  FormGroup,
  Label,
  Input,
  Button,
  Badge,
} from "reactstrap";
import { useNavigate, useLocation, useParams } from "react-router-dom";
import Multiselect from 'multiselect-react-dropdown';

/**
 * ReportBuild2 Component
 * 
 * This component provides an interface for editing report configurations
 * that are based on URL endpoints. It allows users to:
 * - Configure a URL endpoint for data
 * - Set parameters for the report
 * - Enable/disable date filtering
 * - Save configuration changes
 */
const ReportBuild2 = () => {
  // Get report ID from URL params or location state
  const location = useLocation();
  const params = useParams();
  const reportId = params.id || location.state?.reportId;
  const navigate = useNavigate();
  
  // State for form data and related configuration
  const [entryForm, setEntryForm] = useState({
    id: reportId,
    url: "",
    date_param_req: false,
    std_param_html: [],
    adhoc_param_html: "",
  });
  
  // State for UI data and API responses
  const [keysFromUrl, setKeysFromUrl] = useState([]); // Parameters available from URL
  const [databaseList, setDatabaseList] = useState([]); // Available databases
  const [lineId, setLineId] = useState(null); // ID for the report line being edited
  const [builderLineData, setBuilderLineData] = useState([]); // Existing report configuration
  
  /**
   * Load report data when component mounts or reportId changes
   */
  useEffect(() => {
    if (reportId) {
      getReportById(reportId);
    }
  }, [reportId]);

  /**
   * Fetch database list from API
   * Currently not called by default but available for future use
   */
  const fetchDatabaseList = async () => {
    try {
      const response = await ReportBuilderService.getDatabase();
      if (response && response.data) {
        setDatabaseList(response.data);
      }
    } catch (error) {
      console.error("Failed to load database list:", error);
    }
  };

  /**
   * Get report details by ID and populate the form
   * @param {string} id - Report ID to fetch
   */
  const getReportById = async (id) => {
    try {
      const response = await ReportBuilderService.getrbDetailsById(id);
      
      if (!response || !response.data) {
        console.error("No report data found");
        return;
      }
      
      const report = response.data;
      const lineData = report.rpt_builder2_lines || [];
      
      if (lineData.length === 0) {
        console.warn("No report line data found");
        return;
      }
      
      // Store line ID for update operations
      setLineId(lineData[0].id);
      
      // Parse model data if exists
      if (lineData[0].model && lineData[0].model !== '') {
        try {
          const parsedData = JSON.parse(lineData[0].model);
          setBuilderLineData(parsedData);
          
          if (parsedData && parsedData.length > 0) {
            // Handle std_param_html - ensure it's always an array
            const stdParams = parsedData[0].std_param_html || [];
            const stdParamsArray = Array.isArray(stdParams) ? stdParams : 
              (typeof stdParams === 'string' && stdParams.length > 0) ? [stdParams] : [];
              
            // Update form with existing data
            setEntryForm({
              id: lineId,
              std_param_html: stdParamsArray,
              adhoc_param_html: parsedData[0].adhoc_param_html || "",
              date_param_req: parsedData[0].date_param_req || false,
              url: parsedData[0].url || "",
            });
          }
        } catch (parseError) {
          console.error("Error parsing report data:", parseError);
        }
      }
    } catch (error) {
      console.error("Failed to load report details:", error);
    }
  };

  /**
   * Handle form field changes for standard input types
   * @param {Event} e - Input change event
   */
  const handleInputChange = (e) => {
    const { name, value, type, checked } = e.target;
    
    if (type === "select-multiple") {
      // Handle multiple select inputs
      const selectedOptions = Array.from(e.target.selectedOptions, option => option.value);
      setEntryForm(prev => ({
        ...prev,
        [name]: selectedOptions
      }));
    } else {
      // Handle regular inputs and checkboxes
      setEntryForm(prev => ({
        ...prev,
        [name]: type === "checkbox" ? checked : value,
      }));
    }
  };

  /**
   * Handle Multiselect onSelect event for Standard Parameters
   * @param {Array} selectedList - List of selected items
   */
  const handleMultiselectSelect = (selectedList) => {
    setEntryForm(prev => ({
      ...prev,
      std_param_html: selectedList
    }));
  };

  /**
   * Handle Multiselect onRemove event for Standard Parameters
   * @param {Array} selectedList - List of selected items after removal
   */
  const handleMultiselectRemove = (selectedList) => {
    setEntryForm(prev => ({
      ...prev,
      std_param_html: selectedList
    }));
  };

  /**
   * Fetch column keys from provided URL
   * Makes API call to getcolumnDetailsByurl to get available parameters
   * @param {string} url - URL to fetch columns from
   */
  const getKeys = async (url) => {
    if (!url) {
      toast.info("Please enter a URL");
      return;
    }
    
    const loadingToastId = toast.info("Loading...");
    
    try {
      const response = await ReportBuilderService.getcolumnDetailsByurl(url);
      console.log("response: ", response);
      toast.dismiss(loadingToastId);
      
      if (response && response.data) {
        // Update keysFromUrl with the response data
        setKeysFromUrl(response.data);
        // Update adhoc_param_html in the form
        setEntryForm(prev => ({
          ...prev,
          adhoc_param_html: response.data
        }));
        toast.success("Success");
      } else {
        console.warn("No keys found in the URL response");
        toast.info("No data found");
      }
    } catch (error) {
      toast.dismiss(loadingToastId);
      console.error("Failed to fetch keys:", error);
      toast.error("Operation failed");
    }
  };

  /**
   * Handle form submission
   * Validates input and saves report configuration
   * @param {Event} e - Form submit event
   */
  const handleSubmit = async (e) => {
    e.preventDefault();
  
    // Validate required fields
    if (!entryForm.url) {
      toast.info("URL is required");
      return;
    }
    
    if (!lineId) {
      console.error("Missing report line ID");
      toast.error("Operation failed");
      return;
    }
    
    try {
      // Prepare updated builder line data
      const updatedBuilderLineData = [...builderLineData];
      
      // If no existing data, create a new entry
      if (updatedBuilderLineData.length === 0) {
        updatedBuilderLineData.push({});
      }
      
      // Update the first line data
      updatedBuilderLineData[0] = {
        std_param_html: entryForm.std_param_html,
        adhoc_param_html: entryForm.adhoc_param_html,
        date_param_req: entryForm.date_param_req,
        url: entryForm.url,
      };
      
      // Prepare payload for API
      const payload = {
        model: JSON.stringify(updatedBuilderLineData)
      };
      
      // Call API to update report
      await ReportBuilderService.updaterbLineData(payload, lineId);
      toast.success("Report updated successfully");
      
      // Navigate back to the list
      navigate("/admin/reportbuild2all");
    } catch (error) {
      console.error("Failed to update the report:", error);
      toast.error("Update failed");
    }
  };
  
  /**
   * Navigate back to the report list page
   */
  const handleBack = () => {
    navigate("/admin/reportbuild2all");
  };

  /**
   * Remove a parameter from the selected parameters list
   * @param {number} index - Index of parameter to remove
   */
  const handleRemoveParam = (index) => {
    const newParams = entryForm.std_param_html.filter((_, i) => i !== index);
    setEntryForm(prev => ({
      ...prev,
      std_param_html: newParams,
    }));
  };

  return (
    <Container
      className="mt-4 p-4"
      style={{
        maxWidth: "900px",
        backgroundColor: "#ffffff",
        borderRadius: "10px",
        boxShadow: "0 4px 10px rgba(0, 0, 0, 0.2)",
        border: "1px solid #ddd",
        marginBottom: "4rem"
      }}
    >
      {/* Header Section */}
      <h3 className="d-inline" style={{ fontWeight: 300 }}>
        <strong>REPORT SET UP - Project Details Report</strong>
      </h3>
      <Badge color="info" className="ms-3">
        Edit Mode
      </Badge>
      {reportId && (
        <Badge color="primary" className="ms-2">
          ID: {reportId}
        </Badge>
      )}
      <hr />

      {/* Form Section */}
      <Form onSubmit={handleSubmit}>
        <Row>
          {/* URL Input Field */}
          <Col md={6} sm={12} className="mb-4">
            <FormGroup>
              <Label htmlFor="url" className="fw-bold">
                Get URL
              </Label>
              <div className="d-flex align-items-center">
                <Input
                  type="text"
                  id="url"
                  name="url"
                  value={entryForm.url}
                  onChange={handleInputChange}
                  placeholder="Enter URL"
                  className="me-2"
                  style={{ borderColor: "#0E6591" }}
                />
                <Button
                  color="primary"
                  onClick={() => getKeys(entryForm.url)}
                  style={{ backgroundColor: "#0E6591", borderColor: "#0E6591" }}
                >
                  <i className="bi bi-list"></i>
                </Button>
              </div>
            </FormGroup>
          </Col>

          {/* Checkbox for Date Filter */}
          <Col md={6} sm={12} className="mb-4">
            <FormGroup>
              <Label htmlFor="date_param_req" className="fw-bold">
                Include Date Filter
              </Label>
              <div className="d-flex align-items-center">
                <Input
                  type="checkbox"
                  id="date_param_req"
                  name="date_param_req"
                  checked={entryForm.date_param_req}
                  onChange={handleInputChange}
                  className="ms-2"
                />
              </div>
            </FormGroup>
          </Col>

          {/* Standard Parameters Selection */}
          <Col md={6} sm={12} className="mb-4">
            <FormGroup>
              <Label className="fw-bold">Standard Parameters</Label>
              <div>
                              
                {/* Multiselect dropdown for parameters */}
                <Multiselect
                  options={keysFromUrl.map(key => ({ name: key, id: key }))}
                  selectedValues={entryForm.std_param_html.map(param => ({ name: param, id: param }))}
                  onSelect={(selectedList) => handleMultiselectSelect(selectedList.map(item => item.id))}
                  onRemove={(selectedList) => handleMultiselectRemove(selectedList.map(item => item.id))}
                  displayValue="name"
                  placeholder="Select Parameters"
                  showCheckbox={true}
                  style={{ 
                    searchBox: { 
                      borderRadius: '0.25rem',
                      border: '1px solid #0E6591'
                    },
                    chips: {
                      background: "#0E6591"
                    },
                    optionContainer: {
                      borderColor: "#0E6591"
                    }
                  }}
                />
              </div>
            </FormGroup>
          </Col>

          {/* List Dropdown */}
          <Col md={6} sm={12} className="mb-4">
            <FormGroup>
              <Label className="fw-bold">List</Label>
              <Input
                type="select"
                className="form-control"
                style={{ borderColor: "#0E6591" }}
              >
                <option value="">Choose from list</option>
                {databaseList.map((item, index) => (
                  <option key={index} value={item.name}>
                    {item.name}
                  </option>
                ))}
              </Input>
            </FormGroup>
          </Col>
        </Row>

        {/* Action Buttons */}
        <div className="text-center mt-4">
          <Button
            color="secondary"
            outline
            className="me-3"
            onClick={handleBack}
            style={{
              borderColor: "#6c757d",
              color: "#6c757d",
              borderRadius: "20px",
              fontWeight: "bold",
            }}
            type="button"
          >
            BACK
          </Button>
          <Button
            type="submit"
            color="primary"
            style={{
              backgroundColor: "#0E6591",
              borderColor: "#0E6591",
              borderRadius: "20px",
              fontWeight: "bold",
            }}
          >
            UPDATE
          </Button>
        </div>
      </Form>
    </Container>
  );
};

export default ReportBuild2;

