import { mdiChartTimelineVariant, mdiUpload } from '@mdi/js'
import axios from 'axios'
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 FormCheckRadio from '../../components/FormCheckRadio'
import FormCheckRadioGroup from '../../components/FormCheckRadioGroup'
import FormFilePicker from '../../components/FormFilePicker'
import FormImagePicker from '../../components/FormImagePicker'
import { SelectField } from "../../components/SelectField";
import { SelectFieldMany } from "../../components/SelectFieldMany";
import {RichTextField} from "../../components/RichTextField";

import { deleteItem, update, fetch } from '../../stores/projects/projectsSlice'
import { useAppDispatch, useAppSelector } from '../../stores/hooks'
import { useRouter } from 'next/router'
import {saveFile} from "../../helpers/fileSaver";
import dataFormatter from '../../helpers/dataFormatter';
import ImageField from "../../components/ImageField";



const EditProjectsPage = () => {
  const router = useRouter()
  const dispatch = useAppDispatch()
  const initVals = {
      
    
    'name': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'slug': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    
    description: '',
    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    phase: '',
    

    

    

    

    
    
    
    'logo_url': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'favicon_url': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'og_image_url': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    
    theme_config_json: '',
    

    

    

    

    

    

    

    

    

    

    

    
    
    

    
    custom_css_json: '',
    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'cdn_base_url': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'entry_page_slug': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    
    is_deleted: false,
    

    

    

    

    

    

    
    
    

    

    

    

    

    
    deleted_at_time: new Date(),
    

    

    

    

    

    

    

    
    
    
  }
  const [initialValues, setInitialValues] = useState(initVals)
  const [logoAssets, setLogoAssets] = useState<any[]>([])
  const [isLoadingLogoAssets, setIsLoadingLogoAssets] = useState(false)

  const { projects } = useAppSelector((state) => state.projects)
  

  const { id } = router.query

  useEffect(() => {
    dispatch(fetch({ id: id }))
  }, [id])

  const loadLogoAssets = async (projectId: string) => {
    if (!projectId) {
      setLogoAssets([])
      return
    }

    setIsLoadingLogoAssets(true)
    try {
      const response = await axios.get(
        `/assets?limit=500&page=0&sort=desc&field=createdAt&project=${projectId}`,
      )
      const rows = Array.isArray(response?.data?.rows) ? response.data.rows : []
      const taggedLogoAssets = rows.filter(
        (asset: any) =>
          typeof asset?.cdn_url === 'string' &&
          asset.cdn_url &&
          asset?.asset_type === 'image' &&
          typeof asset?.name === 'string' &&
          asset.name.startsWith('[LOGO] '),
      )
      setLogoAssets(taggedLogoAssets)
    } catch (error: any) {
      console.error('Failed to load logo assets for project edit:', error?.message || error)
      setLogoAssets([])
    } finally {
      setIsLoadingLogoAssets(false)
    }
  }

  useEffect(() => {
    if (typeof id === 'string' && id) {
      void loadLogoAssets(id)
      return
    }
    setLogoAssets([])
  }, [id])

  useEffect(() => {
    if (typeof projects === 'object') {
      setInitialValues(projects)
    }
  }, [projects])

  useEffect(() => {
      if (typeof projects === 'object') {
          const newInitialVal = {...initVals};
          Object.keys(initVals).forEach(el => newInitialVal[el] = (projects)[el])
          setInitialValues(newInitialVal);
      }
  }, [projects])

  const handleSubmit = async (data) => {
    await dispatch(update({ id: id, data }))
    await router.push('/projects/projects-list')
  }

  const handleDelete = async () => {
    const projectId = typeof id === 'string' ? id : null

    if (!projectId) {
      return
    }

    if (!window.confirm('Are you sure you want to delete this project?')) {
      return
    }

    await dispatch(deleteItem(projectId))
    await router.push('/projects/projects-list')
  }

  return (
    <>
      <Head>
        <title>{getPageTitle('Edit projects')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiChartTimelineVariant} title={'Edit projects'} main>
        {''}
        </SectionTitleLineWithButton>
        <CardBox>
          <Formik
            enableReinitialize
            initialValues={initialValues}
            onSubmit={(values) => handleSubmit(values)}
          >
            {({ values }) => (
            <Form>


  
    <FormField
        label="Name"
    >
        <Field
            name="name"
            placeholder="Name"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  
    <FormField
        label="Slug"
    >
        <Field
            name="slug"
            placeholder="Slug"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

  

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

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="Phase" labelFor="phase">
        <Field name="phase" id="phase" component="select">
          
            <option value="dev">dev</option>
          
            <option value="stage">stage</option>
          
            <option value="production">production</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  
    <FormField label="Logo">
        <Field name="logo_url" as="select">
          <option value="">{isLoadingLogoAssets ? 'Loading logo options...' : 'Select logo from Assets'}</option>
          {logoAssets.map((asset: any) => (
            <option key={asset.id} value={asset.cdn_url}>
              {(asset.name || '').replace(/^\[[^\]]+\]\s*/, '')}
            </option>
          ))}
          {values.logo_url &&
            !logoAssets.some((asset: any) => asset.cdn_url === values.logo_url) && (
              <option value={values.logo_url}>{values.logo_url}</option>
            )}
        </Field>
    </FormField>
    {values.logo_url && (
      <a className="text-xs underline mt-2 inline-block break-all" href={values.logo_url} target="_blank" rel="noreferrer">
        Preview selected logo
      </a>
    )}
  

  

  

  

  

  

  

  

  

  

  

    

  



  
    <FormField label="Favicon">
        <Field name="favicon_url" as="select">
          <option value="">{isLoadingLogoAssets ? 'Loading logo options...' : 'Select favicon from Assets logos'}</option>
          {logoAssets.map((asset: any) => (
            <option key={asset.id} value={asset.cdn_url}>
              {(asset.name || '').replace(/^\[[^\]]+\]\s*/, '')}
            </option>
          ))}
          {values.favicon_url &&
            !logoAssets.some((asset: any) => asset.cdn_url === values.favicon_url) && (
              <option value={values.favicon_url}>{values.favicon_url}</option>
            )}
        </Field>
    </FormField>
    {values.favicon_url && (
      <a className="text-xs underline mt-2 inline-block break-all" href={values.favicon_url} target="_blank" rel="noreferrer">
        Preview selected favicon
      </a>
    )}
  

  

  

  

  

  

  

  

  

  

  

    

  



  
    <FormField label="OG Image">
        <Field name="og_image_url" as="select">
          <option value="">{isLoadingLogoAssets ? 'Loading logo options...' : 'Select OG image from Assets logos'}</option>
          {logoAssets.map((asset: any) => (
            <option key={asset.id} value={asset.cdn_url}>
              {(asset.name || '').replace(/^\[[^\]]+\]\s*/, '')}
            </option>
          ))}
          {values.og_image_url &&
            !logoAssets.some((asset: any) => asset.cdn_url === values.og_image_url) && (
              <option value={values.og_image_url}>{values.og_image_url}</option>
            )}
        </Field>
    </FormField>
    {values.og_image_url && (
      <a className="text-xs underline mt-2 inline-block break-all" href={values.og_image_url} target="_blank" rel="noreferrer">
        Preview selected OG image
      </a>
    )}
  

  

  

  

  

  

  

  

  

  

  

    

  



  

  
    <FormField label="ThemeconfigJSON" hasTextareaHeight>
        <Field name="theme_config_json" as="textarea" placeholder="ThemeconfigJSON" />
    </FormField>
  

  

  

  

  

  

  

  

  

  

    

  



  

  
    <FormField label="CustomCSSJSON" hasTextareaHeight>
        <Field name="custom_css_json" as="textarea" placeholder="CustomCSSJSON" />
    </FormField>
  

  

  

  

  

  

  

  

  

  

    

  



  
    <FormField
        label="CDNbaseURL"
    >
        <Field
            name="cdn_base_url"
            placeholder="CDNbaseURL"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  
    <FormField
        label="Entrypageslug"
    >
        <Field
            name="entry_page_slug"
            placeholder="Entrypageslug"
        />
    </FormField>
  

  

  

  

  

  

    

  


  

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

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

export default EditProjectsPage
