"use client";

import { useAppSelector } from "@/Redux/Hooks";
import { Button, Col, Form, FormGroup, Input, Label, Row, } from "reactstrap";
import Link from "next/link";
import { ChangeEvent, SyntheticEvent, useEffect, useState } from "react";
import DataService from "@/Config/Axios";
import { toast } from "react-toastify";
import { NewInvoiceInitialValue } from "@/Data/Application/Invoices";
import { ClientInitialValue } from "@/Types/ClientType";
import Select from 'react-select'
import { getDifferenceInDays } from "@/utils/Constants";
import { useRouter } from "next/navigation";
import { currencyOptions } from "@/utils/currencies";

const InvoicesAddForm = () => {
  const { i18LangStatus } = useAppSelector((state) => state.langSlice);
  const [showDueDate, setShowDueDate] = useState(false);
  const [clients, setClients] = useState([]);
  const [data, setData] = useState<any>(NewInvoiceInitialValue)
  const [pdfFile, setPdfFile] = useState()
  const router = useRouter()
  const [loading, setLoading] = useState(false); // Add loading state
  const handleCheckboxChange = () => {
    setShowDueDate(!showDueDate);
  };

  const handleSubmit = async (event: SyntheticEvent) => {
    event.preventDefault()
    setLoading(true); // Set loading state to true on form submit
    const formData = new FormData();

    for (var key in data) {
      formData.append(key, data[key]);
    }
    if (pdfFile) {
      formData.append('pdfFile', pdfFile);
      console.log(pdfFile)
    }
    console.log(formData)
    try {
      const response = await DataService.post(
        '/invoices/create',
        formData,
        { headers: { 'Content-Type': 'multipart/form-data', } }
      )
      console.log(response);
      if (response.data.status) {
        toast.success(response.data.message);
        router.push(`/${i18LangStatus}/invoices`);
      }
      setLoading(false); // Set loading state to false after form submission
    } catch (error: any) {
      setLoading(false); // Set loading state to false in case of an error
      toast.error(error?.response?.data?.message ?? "Something went wrong!")
    }
  };
  const handleChange = (event: ChangeEvent<HTMLInputElement>) => {
    const { name, value } = event.target;
    setData({ ...data, [name]: value })
  }
  const handleSelectChange = (name: string, event: any) => {
    const { label, value } = event;
    setData({ ...data, [name]: value })
  }
  const getClients = async () => {
    try {
      const response = await DataService.post('/clients', { admin: localStorage.getItem("userId") })
      console.log(response)
      if (response.data.status) {
        const formattedClients = await response.data.data.map((client: ClientInitialValue) => ({
          label: client.clientCode + ' - ' + client.firstName + ' ' + client.lastName,
          value: client._id
        }));
        setClients(formattedClients)
      } else {
        toast.error(response.data.message)
      }
    } catch (error: any) {
      toast.error(error?.response?.data?.message ?? "Something went wrong!")
    }
  }
  useEffect(() => {
    getClients()
  }, [])
  console.log(data)
  return (
    <>
      <Form className="theme-form" onSubmit={handleSubmit}>
        <Row>
          <Col sm="4">
            <FormGroup>
              <Label check>
                Client<span className="text-danger">*</span>
              </Label>
              <Select
                required
                onChange={(e: any) => handleSelectChange('clientId', e)}
                options={clients}
                name="clientId"
              >
              </Select>
            </FormGroup>
          </Col>
          <Col sm="4">
            <FormGroup>
              <Label check>
                Reference
              </Label>
              <Input onChange={handleChange} name="reference" />
            </FormGroup>
          </Col>
          <Col sm="4">
            <FormGroup>
              <Label check>
                Invoice #<span className="text-danger">*</span>
              </Label>
              <Input onChange={handleChange} name="clientInvoiceNumber" required />
            </FormGroup>
          </Col>
        </Row>
        <Row>
          <Col sm="4">
            <FormGroup className="d-flex flex-column align-items-stretch">
              <Label check>
                Currency<span className="text-danger">*</span>
              </Label>

              <Select
                required
                onChange={(e: any) => handleSelectChange('currency', e)}
                options={currencyOptions}
                name="currency"
              />
              {/* {countryCurrencyOptions.map((option: any) => (
                        <option value={option.country}>
                          {option.label}
                        </option>
                      ))} */}

              {/* <Select options={countryCurrencyOptions} name="currency" /> */}

            </FormGroup>
          </Col>
          <Col sm="4">
            <FormGroup>
              <Label check>
                Total<span className="text-danger">*</span>
              </Label>

              <Input
                required
                onChange={handleChange}
                name="total"
                className="form-control"
                type="number"
                placeholder=""
              />

            </FormGroup>
          </Col>
          <Col sm="4">
            <FormGroup className="d-flex flex-column align-items-stretch">
              <Label check>
                Amount Open
              </Label>
              <Input
                onChange={handleChange}
                name="pending"
                max={data?.total}
                className="form-control"
                type="number"
                placeholder=""
              />

            </FormGroup>
          </Col>
        </Row>
        <Row>
          <Col sm="4">
            <FormGroup className="d-flex flex-column align-items-stretch">
              <Label check>Invoice Date</Label>
              <Input
                onChange={handleChange}
                name="invoiceDate"
                className="form-control"
                type="date"
                placeholder=""
              />

            </FormGroup>
          </Col>
          <Col sm="4">
            <FormGroup className="d-flex flex-column align-items-stretch">
              <Label check>Expected Payment</Label>
              <Input
                onChange={handleChange}
                name="expectedPayment"
                className="form-control"
                type="date"
                placeholder=""
              />
            </FormGroup>
          </Col>
          <Col sm="1">
            <FormGroup className="d-flex flex-column">
              <Label check>Custom Date</Label>
              <Input
                type="checkbox"
                className=" mt-2"
                onChange={handleCheckboxChange}
                checked={showDueDate}
              />
            </FormGroup>
          </Col>
          {
            !showDueDate ?
              <Col sm="3" className={!showDueDate ? "" : "d-none"}>
                <FormGroup className="d-flex flex-column align-items-stretch">
                  <Label check>Due Date</Label>
                  <Select
                    required
                    onChange={(e: any) => handleSelectChange('dueDate', e)} name="dueDate"
                    options={[{ label: "15", value: "15" }, { label: "30", value: "30" }, { label: "45", value: "45" }, { label: "60", value: "60" }, { label: "75", value: "75" }, { label: "90", value: "90" },]}
                  />
                  {/* <option selected value={0}>Select Date</option>
                        <option value={15}>{"15"}</option>
                        <option value={30}>{"30"}</option>
                        <option value={45}>{"45"}</option>
                        <option value={60}>{"60"}</option>
                        <option value={75}>{"75"}</option>
                        <option value={90}>{"90"}</option> */}

                </FormGroup>
              </Col>
              :
              <Col sm="3" className={!showDueDate ? "d-none" : ""}>
                <FormGroup className="d-flex flex-column align-items-stretch">
                  <Label check>Due Date</Label>
                  <Input
                    onChange={(e: any) => {
                      setData({ ...data, dueDate: getDifferenceInDays(new Date(), e.target.value) });
                      console.log(getDifferenceInDays(new Date(), e.target.value))
                    }
                    }
                    type="date"
                    name="dueDate"
                    className="form-control"
                  ></Input>

                </FormGroup>
              </Col>
          }
        </Row>
        <Row>
          <Col>
            <div className="text-end">
              <Button
                type="submit"
                color="primary"
                className="me-3"
                disabled={loading} // Disable the button when loading is true
              >
                {loading ? "Submitting..." : "Add"} {/* Change button text when loading is true */}
              </Button>
              <Link
                className="btn btn-outline-primary"
                href={`/${i18LangStatus}/invoices`}                        >
                Cancel
              </Link>
            </div>
          </Col>
        </Row>
      </Form>
    </>
  );
};
export default InvoicesAddForm;
