"use client";
import { useAppSelector } from "@/Redux/Hooks";
import { useParams, useRouter } from "next/navigation";
import { Button, Card, CardBody, Col, Container, 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 countryCurrencyOptions from '@/utils/CountryCurrencies.json'
import { getDateDaysAhead, getDifferenceInDays, getFormattedDate, getFormattedDateValue } from "@/utils/Constants";
import { InvoiceInitialValue } from "@/Types/InvoiceType";
import { currencyOptions } from "@/utils/currencies";
import Select from 'react-select'

const InvoicesUpdateForm = () => {
  const router = useRouter();
  const params = useParams()
  const { i18LangStatus } = useAppSelector((state) => state.langSlice);
  const [showDueDate, setShowDueDate] = useState(false);
  const [clients, setClients] = useState([])
  const [invoiceDetails, setInvoiceDetails] = useState<InvoiceInitialValue | any>(NewInvoiceInitialValue)
  const [invoiceFile, setInvoiceFile] = useState<any>()
  const [pdfFile, setPdfFile] = useState()
  const [loading, setLoading] = useState(false)

  const handleCheckboxChange = () => {
    setShowDueDate(!showDueDate);
  };

  const handleSelectChange = (name: string, event: any) => {
    const { label, value } = event;
    setInvoiceDetails({ ...invoiceDetails, [name]: value })
    console.log(value)
  }

  const handleChange = (event: ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {
    const { name, value } = event.target;
    setInvoiceDetails({ ...invoiceDetails, [name]: value })
  }
  const handleSubmit = async (event: SyntheticEvent) => {
    event.preventDefault()
    const formData = new FormData();
    setLoading(true)

    for (var key in invoiceDetails) {
      formData.append(key, invoiceDetails[key]);
    }
    if (pdfFile) {
      formData.append('pdfFile', pdfFile);
      console.log(pdfFile)
    }
    try {
      const response = await DataService.post(`/invoices/update/${params.id}`,
        formData,
        { headers: { 'Content-Type': 'multipart/form-data' } }
      )
      if (response.data.status) {
        toast.success(response.data.message);
        router.back();
      }
      setLoading(false)
    } catch (error: any) {
      setLoading(false)
      toast.error(error?.response?.data?.message ?? "Something went wrong!")
    }
  };

  console.log(invoiceDetails, "Invoice Details")
  const callApi = async () => {
    setLoading(true)
    try {
      const response = await DataService.post(`/invoices/details/${params.id}`)
      let data = response.data.data;
      setInvoiceDetails(data)
      setLoading(false)
    } catch (error: any) {
      setLoading(false)
      toast.error(error.message)
    }
  }
  const getClients = async () => {
    setLoading(true)
    try {
      const response = await DataService.post('/clients')
      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)
      }
      setLoading(false)
    } catch (error: any) {
      setLoading(false)
      toast.error(error?.response?.data?.message ?? "Something went wrong!")
    }
  }
  useEffect(() => {
    callApi()
    getClients()
  }, [])
  console.log(clients)
  return (
    <>
      <Container fluid>
        <Row>
          <Col sm="12">
            <Card>
              <CardBody>
                <Form className="theme-form" onSubmit={handleSubmit}>
                  <Row>
                    <Col sm="3">
                      <FormGroup>
                        <Label check>
                          Invoice Nr.<span className="text-danger">*</span>
                        </Label>
                        <p>
                          <b>
                            {invoiceDetails?.clientInvoiceNumber}
                          </b>
                        </p>
                        {/* <Input onChange={handleChange} name="clientInvoiceNumber" value={invoiceDetails?.clientInvoiceNumber} required /> */}
                      </FormGroup>
                    </Col>
                    <Col sm="3">
                      <FormGroup>
                        <Label check>
                          Internal Transaction Nr.:
                        </Label>
                        <h6>
                          {invoiceDetails.invoiceNumber}
                        </h6>
                      </FormGroup>
                    </Col>
                    <Col sm="3">
                      <FormGroup>
                        <Label check>
                          Client<span className="text-danger">*</span>
                        </Label>
                        <p>
                          <b>
                            {invoiceDetails?.clientId?.firstName} {invoiceDetails?.clientId?.lastName}
                          </b>
                        </p>
                        {/* <select onChange={handleChange} defaultValue={invoiceDetails.clientId} className="form-control form-select" name="clientId">
                          <option value="">Choose Client</option>
                          {clients.map((option: any) => (
                            <option value={option.value} selected={invoiceDetails?.clientId?._id == option.value}>
                              {option.label}
                            </option>
                          ))}
                        </select> */}
                      </FormGroup>
                    </Col>

                    <Col sm="3">
                      <FormGroup className="d-flex flex-column align-items-stretch">
                        <Label check>
                          Status<span className="text-danger">*</span>
                        </Label>
                        <p className="text-capitalize"><b>{invoiceDetails.status}</b></p>
                        {/* <select onChange={handleChange} defaultValue={invoiceDetails.status} className="form-control form-select" name="status">
                          <option value='open'>Open</option>
                          <option value='closed'>Closed</option>
                          <option value='cancelled'>Cancelled</option>
                        </select> */}

                      </FormGroup>
                    </Col>
                    <Col sm="3">
                      <FormGroup>
                        <Label check>
                          Total<span className="text-danger">*</span>
                        </Label>
                        <p><b>
                          {invoiceDetails.total}
                        </b></p>
                        {/* <Input
                          onChange={handleChange}
                          value={invoiceDetails.total}
                          name="total"
                          className="form-control"
                          type="number"
                          placeholder=""
                        /> */}
                      </FormGroup>
                    </Col>
                    <Col sm="3">
                      <FormGroup className="d-flex flex-column align-items-stretch">
                        <Label check>
                          Amount Open<span className="text-danger">*</span>
                        </Label>
                        <p><b>{invoiceDetails.pending}</b></p>
                        {/* <Input
                          onChange={handleChange}
                          value={invoiceDetails.pending}
                          name="pending"
                          className="form-control"
                          type="number"
                          placeholder=""
                        /> */}
                      </FormGroup>
                    </Col>
                  </Row>
                  <br />
                  <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}
                          value={currencyOptions?.find(curren => curren.value == invoiceDetails?.currency?.toLowerCase())}
                          name="currency"
                        // defaultInputValue={invoiceDetails.currency}
                        />
                        {/* <Select options={countryCurrencyOptions} name="currency" /> */}

                      </FormGroup>
                    </Col>
                    <Col sm="4">
                      <FormGroup>
                        <Label check>
                          Reference
                        </Label>
                        <Input onChange={handleChange} value={invoiceDetails?.reference} name="reference" />
                      </FormGroup>
                    </Col>
                    <Col sm="4">
                      <FormGroup className="d-flex flex-column align-items-stretch">
                        <Label check>Invoice Date: </Label>
                        <Input
                          onChange={handleChange}
                          value={getFormattedDateValue(new Date(invoiceDetails?.invoiceDate))}
                          name="invoiceDate"
                          className="form-control"
                          type="date"
                        />

                      </FormGroup>
                    </Col>
                    <Col sm="4">
                      <FormGroup className="d-flex flex-column align-items-stretch">
                        <Label check>Expected Payment</Label>
                        <Input
                          onChange={handleChange}
                          name="expectedPayment"
                          value={getFormattedDateValue(invoiceDetails?.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>
                    <Col sm="3" className={!showDueDate ? "" : "d-none"}>
                      <FormGroup className="">
                        <Label check>Due Date ({invoiceDetails.dueDate} Days)</Label>
                        <select
                          onChange={handleChange}
                          value={invoiceDetails?.dueDate}
                          name="dueDate"
                          className="form-control form-select"
                        >
                          <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>
                        </select>
                      </FormGroup>
                    </Col>
                    <Col sm="3" className={!showDueDate ? "d-none" : ""}>
                      <FormGroup className="">
                        <Label check>Due Date</Label>
                        <Input
                          onChange={(e: any) => setInvoiceDetails({ ...invoiceDetails, dueDate: getDifferenceInDays(new Date(), e.target.value) })}
                          type="date"
                          name="dueDate"
                          className="form-control"
                          value={getFormattedDateValue(getDateDaysAhead(invoiceDetails.dueDate, invoiceDetails?.invoiceDate))}
                        />
                      </FormGroup>
                    </Col>
                    <Col sm="12">
                      <Label>Notes:</Label>
                      <textarea name="notes" onChange={handleChange} className="form-control" rows={5} />
                    </Col>
                    <Col sm="12">
                      <h6 className="fw-bold my-2">Prev Notes:</h6>
                      {
                        invoiceDetails?.notes &&
                        invoiceDetails?.notes.length > 0 &&
                        invoiceDetails?.notes?.map((note: string) =>
                          <p className="fw-light">{note}</p>
                        )}
                    </Col>
                  </Row>
                  <Row className="mt-3">
                    <Col>
                      <div className="text-end">
                        <Button
                          type="submit"
                          color="primary"
                          className="me-3"
                          disabled={loading}
                        >
                          Update
                        </Button>
                        <Link
                          className="btn btn-outline-primary"
                          href={`/${i18LangStatus}/invoices/`}
                        >
                          Cancel
                        </Link>
                      </div>
                    </Col>
                  </Row>
                </Form>
              </CardBody>
            </Card>
          </Col>
        </Row>
      </Container>
    </>
  );
};

export default InvoicesUpdateForm;
