import { mdiAccount, mdiChartTimelineVariant, mdiMail, mdiUpload, mdiAutoFix } from '@mdi/js'
import Head from 'next/head'
import React, { ReactElement } 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, useFormikContext } from 'formik'
import FormField from '../../components/FormField'
import BaseDivider from '../../components/BaseDivider'
import BaseButtons from '../../components/BaseButtons'
import BaseButton from '../../components/BaseButton'
import FormCheckRadio from '../../components/FormCheckRadio'
import FormCheckRadioGroup from '../../components/FormCheckRadioGroup'
import FormFilePicker from '../../components/FormFilePicker'
import FormImagePicker from '../../components/FormImagePicker'
import { SwitchField } from '../../components/SwitchField'

import { SelectField } from '../../components/SelectField'
import { SelectFieldMany } from "../../components/SelectFieldMany";
import {RichTextField} from "../../components/RichTextField";

import { create } from '../../stores/jobs/jobsSlice'
import { useAppDispatch, useAppSelector } from '../../stores/hooks'
import { useRouter } from 'next/router'
import moment from 'moment';
import { askGpt } from '../../stores/openAiSlice'

const initialValues = {
    client: '',
    category: '',
    title: '',
    description: '',
    budget_min: '',
    budget_max: '',
    budget_type: 'fixed',
    deadline_at: '',
    posted_at: '',
    status: 'draft',
    is_remote: false,
    location_requirement: '',
    required_skills: [],
    attachments: [],
}

const AiGenerateButton = () => {
  const { values, setFieldValue } = useFormikContext<any>()
  const dispatch = useAppDispatch()
  const { isAskingQuestion } = useAppSelector((state) => state.openAi)

  const handleAiGenerate = async () => {
    if (!values.title) {
      alert('Please enter a title first')
      return
    }
    const prompt = `Write a professional and detailed job description for a freelance platform called "FreelanceFusion".
    The platform connects students with clients. 
    The job title is: "${values.title}". 
    The description should be structured, clear, and encouraging for student freelancers. 
    Use HTML format for the response (with <h3>, <p>, <ul> tags).`
    
    const resultAction = await dispatch(askGpt(prompt))
    if (askGpt.fulfilled.match(resultAction)) {
      setFieldValue('description', resultAction.payload.data)
    }
  }

  return (
    <BaseButton
      label={isAskingQuestion ? 'Generating...' : 'AI Generate Description'}
      icon={mdiAutoFix}
      color="info"
      outline
      className="mb-2"
      onClick={handleAiGenerate}
      disabled={isAskingQuestion}
    />
  )
}


const JobsNew = () => {
  const router = useRouter()
  const dispatch = useAppDispatch()

  const handleSubmit = async (data) => {
    await dispatch(create(data))
    await router.push('/jobs/jobs-list')
  }

  return (
    <>
      <Head>
        <title>{getPageTitle('New Job')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiChartTimelineVariant} title="New Job" main>
        {''}
        </SectionTitleLineWithButton>
        <CardBox>
          <Formik
            initialValues={initialValues}
            onSubmit={(values) => handleSubmit(values)}
          >
            <Form>
              <FormField label="Client" labelFor="client">
                  <Field name="client" id="client" component={SelectField} options={[]} itemRef={'users'}></Field>
              </FormField>

              <FormField label="Category" labelFor="category">
                  <Field name="category" id="category" component={SelectField} options={[]} itemRef={'service_categories'}></Field>
              </FormField>

              <FormField
                  label="Title"
              >
                  <Field
                      name="title"
                      placeholder="e.g. Video Editing for YouTube Channel"
                  />
              </FormField>

              <div className="flex justify-end">
                <AiGenerateButton />
              </div>

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

              <FormField
                  label="BudgetMin"
              >
                  <Field
                      type="number"
                      name="budget_min"
                      placeholder="BudgetMin"
                  />
              </FormField>

              <FormField
                  label="BudgetMax"
              >
                  <Field
                      type="number"
                      name="budget_max"
                      placeholder="BudgetMax"
                  />
              </FormField>

              <FormField label="BudgetType" labelFor="budget_type">
                  <Field name="budget_type" id="budget_type" component="select">
                    <option value="fixed">fixed</option>
                    <option value="hourly">hourly</option>
                  </Field>
              </FormField>

              <FormField
                  label="DeadlineAt"
              >
                  <Field
                      type="datetime-local"
                      name="deadline_at"
                      placeholder="DeadlineAt"
                  />
              </FormField>

              <FormField
                  label="PostedAt"
              >
                  <Field
                      type="datetime-local"
                      name="posted_at"
                      placeholder="PostedAt"
                  />
              </FormField>

              <FormField label="Status" labelFor="status">
                  <Field name="status" id="status" component="select">
                    <option value="draft">draft</option>
                    <option value="open">open</option>
                    <option value="in_progress">in_progress</option>
                    <option value="in_review">in_review</option>
                    <option value="completed">completed</option>
                    <option value="cancelled">cancelled</option>
                  </Field>
              </FormField>

              <FormField label='IsRemote' labelFor='is_remote'>
                  <Field
                      name='is_remote'
                      id='is_remote'
                      component={SwitchField}
                  ></Field>
              </FormField>

              <FormField
                  label="LocationRequirement"
              >
                  <Field
                      name="location_requirement"
                      placeholder="LocationRequirement"
                  />
              </FormField>

              <FormField label='RequiredSkills' labelFor='required_skills'>
                  <Field
                      name='required_skills'
                      id='required_skills'
                      itemRef={'skills'}
                      options={[]}
                      component={SelectFieldMany}>
                  </Field>
              </FormField>

              <FormField label='Attachments' labelFor='attachments'>
                  <Field
                      name='attachments'
                      id='attachments'
                      itemRef={'job_attachments'}
                      options={[]}
                      component={SelectFieldMany}>
                  </Field>
              </FormField>

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

JobsNew.getLayout = function getLayout(page: ReactElement) {
  return (
      <LayoutAuthenticated permission={'CREATE_JOBS'}>
          {page}
      </LayoutAuthenticated>
  )
}

export default JobsNew