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/proposals/proposalsSlice'
import { useAppDispatch, useAppSelector } from '../../stores/hooks'
import { useRouter } from 'next/router'
import moment from 'moment';
import { askGpt } from '../../stores/openAiSlice'
import axios from 'axios'

const initialValues = {
    job: '',
    freelancer: '',
    cover_letter: '',
    proposed_amount: '',
    pricing_model: 'fixed',
    estimated_days: '',
    status: 'submitted',
    submitted_at: '',
    responded_at: '',
    sample_files: [],
}

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

  const handleAiGenerate = async () => {
    if (!values.job) {
      alert('Please select a job first')
      return
    }

    try {
      // Fetch job details to get context for cover letter
      const jobResponse = await axios.get(`/jobs/${values.job}`)
      const job = jobResponse.data

      const prompt = `Write a professional and compelling cover letter for a student freelancer applying for a job on "FreelanceFusion".
      Job Title: "${job.title}"
      Job Description: "${job.description}"
      
      The cover letter should highlight the student's enthusiasm, relevant (hypothetical) skills, and professional tone. 
      Keep it around 150-200 words.`
      
      const resultAction = await dispatch(askGpt(prompt))
      if (askGpt.fulfilled.match(resultAction)) {
        setFieldValue('cover_letter', resultAction.payload.data)
      }
    } catch (error) {
      console.error('Failed to fetch job or generate cover letter', error)
      alert('Failed to generate cover letter. Please try again.')
    }
  }

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

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

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

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

              <FormField label="Freelancer" labelFor="freelancer">
                  <Field name="freelancer" id="freelancer" component={SelectField} options={[]} itemRef={'users'}></Field>
              </FormField>

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

              <FormField label="CoverLetter" hasTextareaHeight>
                  <Field name="cover_letter" as="textarea" placeholder="Describe why you are the best fit..." className="h-40" />
              </FormField>

              <FormField
                  label="ProposedAmount"
              >
                  <Field
                      type="number"
                      name="proposed_amount"
                      placeholder="ProposedAmount"
                  />
              </FormField>

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

              <FormField
                  label="EstimatedDays"
              >
                  <Field
                      type="number"
                      name="estimated_days"
                      placeholder="EstimatedDays"
                  />
              </FormField>

              <FormField label="Status" labelFor="status">
                  <Field name="status" id="status" component="select">
                    <option value="submitted">submitted</option>
                    <option value="shortlisted">shortlisted</option>
                    <option value="accepted">accepted</option>
                    <option value="rejected">rejected</option>
                    <option value="withdrawn">withdrawn</option>
                  </Field>
              </FormField>

              <FormField
                  label="SubmittedAt"
              >
                  <Field
                      type="datetime-local"
                      name="submitted_at"
                      placeholder="SubmittedAt"
                  />
              </FormField>

              <FormField
                  label="RespondedAt"
              >
                  <Field
                      type="datetime-local"
                      name="responded_at"
                      placeholder="RespondedAt"
                  />
              </FormField>

              <FormField>
                  <Field
                      label='SampleFiles'
                      color='info'
                      icon={mdiUpload}
                      path={'proposals/sample_files'}
                      name='sample_files'
                      id='sample_files'
                      schema={{
                        size: undefined,
                        formats: undefined,
                      }}
                      component={FormFilePicker}
                  ></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('/proposals/proposals-list')}/>
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  )
}

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

export default ProposalsNew