import React, { ReactElement, useEffect, useState } from 'react';
import Head from 'next/head'
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import dayjs from "dayjs";
import {useAppDispatch, useAppSelector} from "../../stores/hooks";
import {useRouter} from "next/router";
import { fetch } from '../../stores/jobs/jobsSlice'
import {saveFile} from "../../helpers/fileSaver";
import dataFormatter from '../../helpers/dataFormatter';
import ImageField from "../../components/ImageField";
import LayoutAuthenticated from "../../layouts/Authenticated";
import {getPageTitle} from "../../config";
import SectionTitleLineWithButton from "../../components/SectionTitleLineWithButton";
import SectionMain from "../../components/SectionMain";
import CardBox from "../../components/CardBox";
import BaseButton from "../../components/BaseButton";
import BaseDivider from "../../components/BaseDivider";
import {mdiChartTimelineVariant, mdiAlertCircle} from "@mdi/js";
import {SwitchField} from "../../components/SwitchField";
import FormField from "../../components/FormField";
import axios from 'axios';


const JobsView = () => {
    const router = useRouter()
    const dispatch = useAppDispatch()
    const { jobs } = useAppSelector((state) => state.jobs)
    const [disputing, setDisputing] = useState(false);

    const { id } = router.query;
    
    function removeLastCharacter(str) {
      console.log(str,`str`)
      return str.slice(0, -1);
    }

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

    const handleDispute = async () => {
        if (!confirm('Are you sure you want to raise a dispute? This will pause escrow release and alert the admins.')) return;
        setDisputing(true);
        try {
            await axios.post(`/jobs/${id}/dispute`);
            alert('Dispute raised successfully. Escrow is paused.');
            dispatch(fetch({ id })); // Refresh job details
        } catch (error) {
            console.error('Error raising dispute:', error);
            alert('Failed to raise dispute.');
        } finally {
            setDisputing(false);
        }
    };


    return (
      <>
          <Head>
              <title>{getPageTitle('View jobs')}</title>
          </Head>
          <SectionMain>
            <SectionTitleLineWithButton icon={mdiChartTimelineVariant} title={removeLastCharacter('View jobs')} main>
                <div className="flex items-center gap-2">
                    {jobs?.status !== 'Disputed' && (
                        <BaseButton
                            color='danger'
                            label={disputing ? 'Processing...' : 'Raise Dispute'}
                            icon={mdiAlertCircle}
                            onClick={handleDispute}
                            disabled={disputing}
                        />
                    )}
                    <BaseButton
                      color='info'
                      label='Edit'
                      href={`/jobs/jobs-edit/?id=${id}`}
                    />
                </div>
            </SectionTitleLineWithButton>
            <CardBox>
            
              
                <div className={'mb-4'}>
                    <p className={'block font-bold mb-2'}>Client</p>
                    <p>{jobs?.client?.firstName ?? 'No data'}</p>
                </div>
                 
              
                <div className={'mb-4'}>
                    <p className={'block font-bold mb-2'}>Category</p>
                    <p>{jobs?.category?.name ?? 'No data'}</p>
                </div>
                 
              
                <div className={'mb-4'}>
                    <p className={'block font-bold mb-2'}>Title</p>
                    <p>{jobs?.title}</p>
                </div>
              
                <div className={'mb-4'}>
                  <p className={'block font-bold mb-2'}>Description</p>
                  {jobs.description
                    ? <p dangerouslySetInnerHTML={{__html: jobs.description}}/>
                    : <p>No data</p>
                  }
                </div>
              
                <div className={'mb-4'}>
                  <p className={'block font-bold mb-2'}>BudgetMin</p>
                  <p>{jobs?.budget_min || 'No data'}</p>
                </div>
              
                <div className={'mb-4'}>
                  <p className={'block font-bold mb-2'}>BudgetMax</p>
                  <p>{jobs?.budget_max || 'No data'}</p>
                </div>
              
                <div className={'mb-4'}>
                    <p className={'block font-bold mb-2'}>BudgetType</p>
                    <p>{jobs?.budget_type ?? 'No data'}</p>
                </div>
              
                <FormField label='DeadlineAt'>
                    {jobs.deadline_at ? <DatePicker
                      dateFormat="yyyy-MM-dd hh:mm"
                      showTimeSelect
                      selected={jobs.deadline_at ?
                        new Date(
                          dayjs(jobs.deadline_at).format('YYYY-MM-DD hh:mm'),
                        ) : null
                      }
                      disabled
                    /> : <p>No DeadlineAt</p>}
                </FormField>
              
                <FormField label='PostedAt'>
                    {jobs.posted_at ? <DatePicker
                      dateFormat="yyyy-MM-dd hh:mm"
                      showTimeSelect
                      selected={jobs.posted_at ?
                        new Date(
                          dayjs(jobs.posted_at).format('YYYY-MM-DD hh:mm'),
                        ) : null
                      }
                      disabled
                    /> : <p>No PostedAt</p>}
                </FormField>
              
                <div className={'mb-4'}>
                    <p className={'block font-bold mb-2'}>Status</p>
                    <p className={`font-bold ${jobs?.status === 'Disputed' ? 'text-red-500' : ''}`}>{jobs?.status ?? 'No data'}</p>
                </div>
              
                <FormField label='IsRemote'>
                    <SwitchField
                      field={{name: 'is_remote', value: jobs?.is_remote}}
                      form={{setFieldValue: () => null}}
                      disabled
                    />
                </FormField>
              
                <div className={'mb-4'}>
                    <p className={'block font-bold mb-2'}>LocationRequirement</p>
                    <p>{jobs?.location_requirement}</p>
                </div>
              
                <>
                    <p className={'block font-bold mb-2'}>RequiredSkills</p>
                    <CardBox
                      className='mb-6 border border-gray-300 rounded overflow-hidden'
                      hasTable
                    >
                        <div className='overflow-x-auto'>
                            <table>
                            <thead>
                            <tr>
                                
                                    <th>Name</th>
                                    <th>Category</th>
                                    <th>Description</th>
                                    <th>IsActive</th>
                            </tr>
                            </thead>
                            <tbody>
                            {jobs.required_skills && Array.isArray(jobs.required_skills) &&
                              jobs.required_skills.map((item: any) => (
                                <tr key={item.id} onClick={() => router.push(`/skills/skills-view/?id=${item.id}`)}>
                                    <td data-label="name">
                                        { item.name }
                                    </td>
                                    <td data-label="category">
                                        { item.category }
                                    </td>
                                    <td data-label="description">
                                        { item.description }
                                    </td>
                                    <td data-label="is_active">
                                        { dataFormatter.booleanFormatter(item.is_active) }
                                    </td>
                                </tr>
                              ))}
                            </tbody>
                        </table>
                        </div>
                        {!jobs?.required_skills?.length && <div className={'text-center py-4'}>No data</div>}
                    </CardBox>
                </>

                <>
                    <p className={'block font-bold mb-2'}>Attachments</p>
                    <CardBox
                      className='mb-6 border border-gray-300 rounded overflow-hidden'
                      hasTable
                    >
                        <div className='overflow-x-auto'>
                            <table>
                            <thead>
                            <tr>
                                    <th>Caption</th>
                                    <th>UploadedAt</th>
                            </tr>
                            </thead>
                            <tbody>
                            {jobs.attachments && Array.isArray(jobs.attachments) &&
                              jobs.attachments.map((item: any) => (
                                <tr key={item.id} onClick={() => router.push(`/job_attachments/job_attachments-view/?id=${item.id}`)}>
                                    <td data-label="caption">
                                        { item.caption }
                                    </td>
                                    <td data-label="uploaded_at">
                                        { dataFormatter.dateTimeFormatter(item.uploaded_at) }
                                    </td>
                                </tr>
                              ))}
                            </tbody>
                        </table>
                        </div>
                        {!jobs?.attachments?.length && <div className={'text-center py-4'}>No data</div>}
                    </CardBox>
                </>
              
                <>
                    <p className={'block font-bold mb-2'}>Job_attachments Job</p>
                    <CardBox
                      className='mb-6 border border-gray-300 rounded overflow-hidden'
                      hasTable
                    >
                        <div className='overflow-x-auto'>
                            <table>
                            <thead>
                            <tr>
                                <th>Caption</th>
                                <th>UploadedAt</th>
                            </tr>
                            </thead>
                            <tbody>
                            {jobs.job_attachments_job && Array.isArray(jobs.job_attachments_job) &&
                              jobs.job_attachments_job.map((item: any) => (
                                <tr key={item.id} onClick={() => router.push(`/job_attachments/job_attachments-view/?id=${item.id}`)}>
                                    <td data-label="caption">
                                        { item.caption }
                                    </td>
                                    <td data-label="uploaded_at">
                                        { dataFormatter.dateTimeFormatter(item.uploaded_at) }
                                    </td>
                                </tr>
                              ))}
                            </tbody>
                        </table>
                        </div>
                        {!jobs?.job_attachments_job?.length && <div className={'text-center py-4'}>No data</div>}
                    </CardBox>
                </>
                
                <>
                    <p className={'block font-bold mb-2'}>Proposals Job</p>
                    <CardBox
                      className='mb-6 border border-gray-300 rounded overflow-hidden'
                      hasTable
                    >
                        <div className='overflow-x-auto'>
                            <table>
                            <thead>
                            <tr>
                                <th>CoverLetter</th>
                                <th>ProposedAmount</th>
                                <th>PricingModel</th>
                                <th>EstimatedDays</th>
                                <th>Status</th>
                                <th>SubmittedAt</th>
                                <th>RespondedAt</th>
                            </tr>
                            </thead>
                            <tbody>
                            {jobs.proposals_job && Array.isArray(jobs.proposals_job) &&
                              jobs.proposals_job.map((item: any) => (
                                <tr key={item.id} onClick={() => router.push(`/proposals/proposals-view/?id=${item.id}`)}>
                                    <td data-label="cover_letter">
                                        { item.cover_letter }
                                    </td>
                                    <td data-label="proposed_amount">
                                        { item.proposed_amount }
                                    </td>
                                    <td data-label="pricing_model">
                                        { item.pricing_model }
                                    </td>
                                    <td data-label="estimated_days">
                                        { item.estimated_days }
                                    </td>
                                    <td data-label="status">
                                        { item.status }
                                    </td>
                                    <td data-label="submitted_at">
                                        { dataFormatter.dateTimeFormatter(item.submitted_at) }
                                    </td>
                                    <td data-label="responded_at">
                                        { dataFormatter.dateTimeFormatter(item.responded_at) }
                                    </td>
                                </tr>
                              ))}
                            </tbody>
                        </table>
                        </div>
                        {!jobs?.proposals_job?.length && <div className={'text-center py-4'}>No data</div>}
                    </CardBox>
                </>
                
                <>
                    <p className={'block font-bold mb-2'}>Contracts Job</p>
                    <CardBox
                      className='mb-6 border border-gray-300 rounded overflow-hidden'
                      hasTable
                    >
                        <div className='overflow-x-auto'>
                            <table>
                            <thead>
                            <tr>
                                <th>Status</th>
                                <th>AgreedAmount</th>
                                <th>PricingModel</th>
                                <th>StartedAt</th>
                                <th>CompletedAt</th>
                                <th>Terms</th>
                                <th>RevisionLimit</th>
                            </tr>
                            </thead>
                            <tbody>
                            {jobs.contracts_job && Array.isArray(jobs.contracts_job) &&
                              jobs.contracts_job.map((item: any) => (
                                <tr key={item.id} onClick={() => router.push(`/contracts/contracts-view/?id=${item.id}`)}>
                                    <td data-label="status">
                                        { item.status }
                                    </td>
                                    <td data-label="agreed_amount">
                                        { item.agreed_amount }
                                    </td>
                                    <td data-label="pricing_model">
                                        { item.pricing_model }
                                    </td>
                                    <td data-label="started_at">
                                        { dataFormatter.dateTimeFormatter(item.started_at) }
                                    </td>
                                    <td data-label="completed_at">
                                        { dataFormatter.dateTimeFormatter(item.completed_at) }
                                    </td>
                                    <td data-label="terms">
                                        { item.terms }
                                    </td>
                                    <td data-label="revision_limit">
                                        { item.revision_limit }
                                    </td>
                                </tr>
                              ))}
                            </tbody>
                        </table>
                        </div>
                        {!jobs?.contracts_job?.length && <div className={'text-center py-4'}>No data</div>}
                    </CardBox>
                </>

                <BaseDivider />

                <BaseButton
                    color='info'
                    label='Back'
                    onClick={() => router.push('/jobs/jobs-list')}
                />
              </CardBox>
          </SectionMain>
      </>
    );
};

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

export default JobsView;