import { mdiChartTimelineVariant, mdiArrowLeft } 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 { 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 FormFilePicker from '../../components/FormFilePicker'
import { SelectField } from '../../components/SelectField'
import { SelectFieldMany } from "../../components/SelectFieldMany";
import { RichTextField } from "../../components/RichTextField";
import { create, update, fetch } from '../../stores/projects/projectsSlice'
import { useAppDispatch, useAppSelector } from '../../stores/hooks'
import { useRouter } from 'next/router'
import moment from 'moment';
import { hasPermission } from "../../helpers/userPermissions";

const ProjectsForm = () => {
  const router = useRouter()
  const dispatch = useAppDispatch()
  const { id } = router.query
  const isNew = id === 'new'
  
  const { projects: projectData, loading } = useAppSelector((state) => state.projects)
  const [initialValues, setInitialValues] = useState({
    name: '',
    status: 'active',
    description: '',
    startDate: '',
    endDate: '',
    trials: [],
    documentation: [],
    tenant: '', // Optional/Tenant logic
    organizations: '', // Optional/Org logic
  })

  useEffect(() => {
    if (id && !isNew) {
      dispatch(fetch({ id }))
    }
  }, [id, isNew, dispatch])

  useEffect(() => {
    if (!isNew && projectData && projectData.id === id) {
       setInitialValues({
         name: projectData.name || '',
         status: projectData.status || 'active',
         description: projectData.description || '',
         startDate: projectData.startDate ? moment(projectData.startDate).format('YYYY-MM-DDTHH:mm') : '',
         endDate: projectData.endDate ? moment(projectData.endDate).format('YYYY-MM-DDTHH:mm') : '',
         trials: projectData.trials || [],
         documentation: projectData.documentation || [],
         tenant: projectData.tenant?.id || '',
         organizations: projectData.organizations?.id || '',
       })
    }
  }, [projectData, id, isNew])

  const handleSubmit = async (values) => {
    try {
      if (isNew) {
        await dispatch(create(values)).unwrap()
      } else {
        await dispatch(update({ id, data: values })).unwrap()
      }
      await router.push('/projects/projects-list')
    } catch (error) {
      console.error('Failed to save project:', error)
    }
  }

  const title = isNew ? 'New Project' : 'Edit Project'

  return (
    <>
      <Head>
        <title>{getPageTitle(title)}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiChartTimelineVariant} title={title} main>
            <BaseButton
                href={'/projects/projects-list'}
                icon={mdiArrowLeft}
                color="whiteDark"
                label="Back"
                roundedFull
                small
            />
        </SectionTitleLineWithButton>
        <CardBox>
          <Formik
            enableReinitialize
            initialValues={initialValues}
            onSubmit={(values) => handleSubmit(values)}
          >
            {({ values, setFieldValue }) => (
            <Form>
              <FormField label="Name" labelFor="name">
                  <Field name="name" placeholder="Project Name" id="name" />
              </FormField>

              <FormField label="Status" labelFor="status">
                  <Field name="status" id="status" component="select">
                    <option value="active">Active</option>
                    <option value="completed">Completed</option>
                    <option value="archived">Archived</option>
                  </Field>
              </FormField>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <FormField label="Start Date" labelFor="startDate">
                      <Field
                          type="datetime-local"
                          name="startDate"
                          id="startDate"
                      />
                  </FormField>

                  <FormField label="Finish Date" labelFor="endDate">
                      <Field
                          type="datetime-local"
                          name="endDate"
                          id="endDate"
                      />
                  </FormField>
              </div>

              <FormField label='Description' hasTextareaHeight>
                  <Field
                      name='description'
                      id='description'
                      component={RichTextField}
                  ></Field>
              </FormField>

              <FormField label='Associated Trials' labelFor='trials'>
                  <Field
                      name='trials'
                      id='trials'
                      itemRef={'trials'}
                      options={[]}
                      component={SelectFieldMany}>
                  </Field>
              </FormField>
              
              <FormField label="Supporting Documentation" labelFor="documentation">
                  <Field
                    component={FormFilePicker}
                    path="projects/documentation" // Path for upload
                    name="documentation"
                    field={{ name: 'documentation', value: values.documentation }}
                    form={{ setFieldValue }}
                    schema={{
                        size: 1024 * 1024 * 10, // 10MB
                        formats: [ 'application/pdf', 'image/jpeg', 'image/png', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'text/csv', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ]
                    }}
                    accept="*"
                    label="Upload File"
                    color="info"
                  />
              </FormField>

              <BaseDivider />
              <BaseButtons>
                <BaseButton type="submit" color="info" label="Submit" loading={loading} />
                <BaseButton type="reset" color="info" outline label="Reset" />
                <BaseButton type='button' color='danger' outline label='Cancel' onClick={() => router.push('/projects/projects-list')}/>
              </BaseButtons>
            </Form>
            )}
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  )
}

ProjectsForm.getLayout = function getLayout(page: ReactElement) {
  return (
      <LayoutAuthenticated
          permission={'READ_PROJECTS'} // Or CREATE/UPDATE depending on mode, but READ is safer base
      >
          {page}
      </LayoutAuthenticated>
  )
}

export default ProjectsForm
