import { Col, Row, Form } from "react-bootstrap";
import { getPorts, getDayoutAvg } from "@/services/public";
import React, { useEffect, useState } from "react";
import DatePicker from "react-datepicker";
import Moment from "moment";
import { signOut, useSession } from "next-auth/react";
import "react-datepicker/dist/react-datepicker.css";
import { useRouter } from "next/router";
import { toast } from "react-toastify";
import { ScaleLoader } from "react-spinners";
import ProtectedRoute from "@/publicRoute";

interface PortType {
  id: number | string | null;
  name: string | null;
  state_code: string | null;
  zip: string | null;
  mode: string | null;
  lat: string | null;
  lng: string | null;
}

type DateType = Date | null;

function SpotRateAvg() {
  const { data } = useSession();
  const Router = useRouter();

  const [portsData, setPortsData] = useState([]);
  const [selectedPort, setSelectedPort] = useState<string>("");
  const [loading, setLoading] = useState<boolean>(false);
  const [arrayData, setArrayData] = useState([]);
  let today = new Date();

  const [endDate, setEndDate] = useState<DateType>(null);

  const [startDate, setStartDate] = useState<DateType>(null);

  function getNewDateLessWithSixMonthsLesser() {
    let currentDate = new Date();
    currentDate.setMonth(currentDate.getMonth() - 1);

    return currentDate;
  }

  const handleDateChange = (dates: DateType[]) => {
    const [start, end] = dates;
    setStartDate(start);
    setEndDate(end);
    if (selectedPort) {
      makeApiCall(selectedPort, start, end);
    }
  };

  function dateRange(start_date: Date, end_date: Date): string[] {
    var result = [];
    let startMon = Moment(start_date);
    let endMon = Moment(end_date).add(1, "month");

    if (endMon.isBefore(startMon)) {
      alert("End date must be greated than start date.");
    }

    if (endMon.diff(startMon, "year") >= 1) {
      while (startMon.isBefore(endMon)) {
        result.push(startMon.format("MMMM-yy"));
        startMon.add(1, "month");
      }
    } else {
      while (startMon.isBefore(endMon)) {
        result.push(startMon.format("MMMM"));
        startMon.add(1, "month");
      }
    }
    return result;
  }

  const renderData =
    arrayData?.length > 0 ? (
      <ul>
        {arrayData.map(
          (
            {
              port_name,
              day_out_avg,
            }: { port_name: string; day_out_avg: string },
            index: number,
          ) => (
            <li key={index}>
              {port_name}
              <span>{day_out_avg}</span>
            </li>
          ),
        )}
      </ul>
    ) : (
      <div className="emptydata">
        {" "}
        <h6 className="text-center mt-4 fs-14">No data found</h6>
      </div>
    );

  function makeApiCall(
    portId: string | number,
    startDatee: Date,
    endDatee: Date,
  ) {
    setLoading(true);
    const start_dates = Moment(startDatee).format("YYYY-MM");
    const end_dates = Moment(endDatee).format("YYYY-MM");
    const queryString = `port_id=${portId}&start_date=${end_dates}&end_date=${start_dates}`;
    getDayoutAvg(data?.user?.image, queryString)
      .then((resp) => {
        setLoading(false);

        if (resp?.status === "success") {
          setArrayData([resp?.data]);
        }
      })
      .catch((err) => {
        setLoading(false);
        toast.error(err.message, {
          position: toast.POSITION.TOP_CENTER,
        });
      });
  }

  useEffect(() => {
    if (selectedPort.length > 0) {
      if (!data?.user?.image) {
        toast.error("Token Expired, Please Login again.", {
          position: toast.POSITION.TOP_CENTER,
        });
        signOut({ redirect: false }).then(() => {
          Router.push("/login");
        });

        return;
      }
      makeApiCall(
        `${selectedPort}`,
        getNewDateLessWithSixMonthsLesser(),
        today,
      );
    }
  }, [selectedPort]);

  useEffect(() => {
    if (startDate && endDate && selectedPort.length > 0) {
      makeApiCall(selectedPort, startDate, endDate);
    }
  }, [endDate, startDate, selectedPort]);

  useEffect(() => {
    getPorts().then((response) => {
      if (response.status == "success") {
        setPortsData(response.data);
      }
    });
  }, []);

  const handleReset = () => {
    setSelectedPort("");
    setStartDate(null);
    setEndDate(null);
  };

  return (
    <div className="chart_block">
      <div className="port_ramp_tow">
        <h3>“Days Out” Avg. for Capacity</h3>
      </div>
      <Row>
        <Col xs={6} className="pe-1">
          <div className="form_body">
            <Form.Label className="form-label" htmlFor="port_ramp">
              Market
            </Form.Label>
            <Form.Select
              className={`form-select-sm pe-1 `}
              id="port_ramp"
              value={selectedPort}
              onChange={(e: any) => setSelectedPort(e.target.value)}
            >
              <option value="">Select Market</option>
              {portsData?.map((item: any) => {
                return (
                  <option key={item.id} value={item.id}>
                    {item.state_code}-{item.name}
                  </option>
                );
              })}
            </Form.Select>
          </div>
        </Col>
        <Col xs={6} className="ps-1">
          <div className="form_body">
            <Form.Label className="form-label">Select Date Range</Form.Label>
            <div className="">
              <DatePicker
                className="form-select form-select-sm pe-0 py-1 fs-14"
                selected={startDate}
                onChange={handleDateChange}
                startDate={startDate}
                endDate={endDate}
                selectsRange
                showMonthYearPicker
                dateFormat="MM/yyyy"
                disabled={selectedPort.length === 0}
                maxDate={Moment().toDate()}
              />
            </div>
          </div>
        </Col>
      </Row>
      <Row className="mt-1">
        <Col xs={6}></Col>
        <Col xs={6} className="text-end clear_all_text_card">
          <button
            className="border-bottom fs-12 pe-auto text-danger text-uppercase"
            style={{ all: "unset" }}
            onClick={handleReset}
          >
            Clear All
          </button>
        </Col>
      </Row>

      {selectedPort.length > 0 && (
        <>
          <Row>
            <div className="form_body">
              <div className="port_ramp">
                <h3>Port / Ramp</h3>
                <button className="sort_btn">Days Out</button>
              </div>
            </div>
          </Row>
          {loading ? (
            <div className="text-center">
              <ScaleLoader color="#3180f3" />
            </div>
          ) : (
            <div className="content_text">
              <div className="content_text">
                <ul>{renderData}</ul>
              </div>
            </div>
          )}
        </>
      )}

      {selectedPort.length === 0 && (
        <h6 className="text-center mt-4 fs-14">Please Select Market </h6>
      )}
    </div>
  );
}

export default ProtectedRoute(SpotRateAvg);
