import { mdiPencil } from '@mdi/js';
import Head from 'next/head';
import React, { ReactElement, useEffect, useState } from 'react';
import CardBox from '../components/CardBox';
import LayoutAuthenticated from '../layouts/Authenticated';
import SectionMain from '../components/SectionMain';
import SectionTitleLineWithButton from '../components/SectionTitleLineWithButton';
import JobLogPayPreview from '../components/JobLogPayPreview';
import { getPageTitle } from '../config';

import { Field, Form, Formik } from 'formik';
import FormField from '../components/FormField';
import BaseDivider from '../components/BaseDivider';
import BaseButtons from '../components/BaseButtons';
import BaseButton from '../components/BaseButton';
import { SelectField } from '../components/SelectField';
import { useRouter } from 'next/router';
import { create } from '../stores/job_logs/job_logsSlice';
import { useAppDispatch, useAppSelector } from '../stores/hooks';
import axios from 'axios';

const LogWorkPage = () => {
  const router = useRouter();
  const dispatch = useAppDispatch();
  const currentUser = useAppSelector((state) => state.auth.currentUser);
  const [assignedPayTypes, setAssignedPayTypes] = useState<any[]>([]);

  useEffect(() => {
    if (currentUser?.id) {
      axios
        .get(`/employee_pay_types?employee=${currentUser.id}&active=true`)
        .then((res) => {
          if (res.data && res.data.rows) {
            const payTypes = res.data.rows
              .map((row: any) => row.pay_type)
              .filter(Boolean);
            setAssignedPayTypes(payTypes);
          }
        })
        .catch((err) => console.error('Failed to fetch assigned pay types:', err));
    }
  }, [currentUser]);

  const initialValues = {
    work_date: new Date().toISOString().slice(0, 10),
    employee: currentUser?.id || '',
    customer: '',
    hours_conducted: '',
    client_paid: '',
    workersCompClass: '',
    pay_type: '',
    vehicle: '',
    status: 'submitted',
    notes_to_admin: '',
  };

  const handleSubmit = async (data: any) => {
    await dispatch(create(data));
    await router.push('/my-logs');
  };

  return (
    <>
      <Head>
        <title>{getPageTitle('Log Work')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiPencil} title="Log Work" main>
          {''}
        </SectionTitleLineWithButton>
        <CardBox>
          <Formik initialValues={initialValues} onSubmit={(values) => handleSubmit(values)}>
            {() => (
              <Form>
                <FormField label="Work Date">
                  <Field type="date" name="work_date" />
                </FormField>
                <FormField label="Customer" labelFor="customer">
                  <Field name="customer" id="customer" placeholder="Enter customer name" />
                </FormField>
                <FormField label="Hours Conducted">
                  <Field type="number" name="hours_conducted" placeholder="Hours" />
                </FormField>
                <FormField label="Client Paid">
                  <Field type="number" name="client_paid" placeholder="Amount" />
                </FormField>
                <FormField label="Worker's Comp Class" labelFor="workersCompClass">
                  <Field
                    name="workersCompClass"
                    id="workersCompClass"
                    component={SelectField}
                    options={[]}
                    itemRef={'workers_comp_classes'}
                    showField={'name'}
                  />
                </FormField>
                <FormField label="Pay Type" labelFor="pay_type">
                  <Field name="pay_type" id="pay_type" as="select">
                    <option value="">Select an assigned pay type</option>
                    {assignedPayTypes.map((pt) => (
                      <option key={pt.id} value={pt.id}>
                        {pt.name || pt.pay_method}
                      </option>
                    ))}
                  </Field>
                </FormField>
                <JobLogPayPreview payTypeOptions={assignedPayTypes} />
                <FormField label="Vehicle" labelFor="vehicle">
                  <Field
                    name="vehicle"
                    id="vehicle"
                    component={SelectField}
                    options={[]}
                    itemRef={'vehicles'}
                  />
                </FormField>
                <FormField label="Notes to Admin" hasTextareaHeight>
                  <Field name="notes_to_admin" as="textarea" placeholder="Notes..." />
                </FormField>

                <BaseDivider />
                <BaseButtons>
                  <BaseButton type="submit" color="info" label="Submit Work Log" />
                </BaseButtons>
              </Form>
            )}
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  );
};

LogWorkPage.getLayout = function getLayout(page: ReactElement) {
  return <LayoutAuthenticated>{page}</LayoutAuthenticated>;
};

export default LogWorkPage;
