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/leads/leadsSlice'
import dataFormatter from '../../helpers/dataFormatter';
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, mdiMessageReply, mdiAccountMultiple, mdiCamera, mdiTimelineText, mdiInformation} from "@mdi/js";
import FormField from "../../components/FormField";
import BaseIcon from "../../components/BaseIcon";
import ImageField from "../../components/ImageField";


const LeadsView = () => {
    const router = useRouter()
    const dispatch = useAppDispatch()
    const { leads } = useAppSelector((state) => state.leads)
    const { currentUser } = useAppSelector((state) => state.auth);
    const isBusinessOwner = currentUser?.app_role?.name === 'Verified Business Owner';

    const { id } = router.query;
    
    const [activeTab, setActiveTab] = useState('details');

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

    const tabs = [
        { id: 'details', label: 'Details', icon: mdiInformation },
        { id: 'photos', label: 'Photos', icon: mdiCamera },
        { id: 'matches', label: 'Matches', icon: mdiAccountMultiple },
        { id: 'events', label: 'Events', icon: mdiTimelineText },
    ];

    return (
      <>
          <Head>
              <title>{getPageTitle('View Service Request')}</title>
          </Head>
          <SectionMain>
            <SectionTitleLineWithButton icon={mdiChartTimelineVariant} title={'View Service Request'} main>
                <div className="flex space-x-2">
                    {isBusinessOwner && (
                        <BaseButton
                            color='success'
                            label='Respond'
                            icon={mdiMessageReply}
                            href={`/messages/messages-new/?leadId=${id}&receiverId=${leads?.user?.id}`}
                        />
                    )}
                    <BaseButton
                        color='info'
                        label='Edit'
                        href={`/leads/leads-edit/?id=${id}`}
                    />
                </div>
            </SectionTitleLineWithButton>

            <div className="mb-6 flex space-x-4 border-b border-gray-200">
                {tabs.map((tab) => (
                    <button
                        key={tab.id}
                        onClick={() => setActiveTab(tab.id)}
                        className={`flex items-center space-x-2 pb-2 px-1 transition-colors ${
                            activeTab === tab.id
                                ? 'border-b-2 border-blue-600 text-blue-600'
                                : 'text-gray-500 hover:text-gray-700'
                        }`}
                    >
                        <BaseIcon path={tab.icon} size={18} />
                        <span>{tab.label}</span>
                    </button>
                ))}
            </div>

            {activeTab === 'details' && (
                <CardBox>
                    <div className={'grid grid-cols-1 md:grid-cols-2 gap-6'}>
                        <div className={'mb-4'}>
                            <p className={'block font-bold mb-2'}>User</p>
                            <p>{leads?.user?.firstName} {leads?.user?.lastName}</p>
                        </div>

                        <div className={'mb-4'}>
                            <p className={'block font-bold mb-2'}>Category</p>
                            <p>{leads?.category?.name ?? 'No data'}</p>
                        </div>

                        <div className={'mb-4'}>
                            <p className={'block font-bold mb-2'}>Keyword</p>
                            <p>{leads?.keyword}</p>
                        </div>

                        <div className={'mb-4'}>
                            <p className={'block font-bold mb-2'}>Urgency</p>
                            <p>{leads?.urgency ?? 'No data'}</p>
                        </div>

                        <div className={'mb-4'}>
                            <p className={'block font-bold mb-2'}>Status</p>
                            <p>{leads?.status ?? 'No data'}</p>
                        </div>
                    </div>

                    <FormField label='Description' hasTextareaHeight>
                        <textarea className={'w-full'} disabled value={leads?.description} />
                    </FormField>

                    <div className={'grid grid-cols-1 md:grid-cols-2 gap-6'}>
                        <div className={'mb-4'}>
                            <p className={'block font-bold mb-2'}>Contact Name</p>
                            <p>{leads?.contact_name}</p>
                        </div>

                        <div className={'mb-4'}>
                            <p className={'block font-bold mb-2'}>Contact Phone</p>
                            <p>{leads?.contact_phone}</p>
                        </div>

                        <div className={'mb-4'}>
                            <p className={'block font-bold mb-2'}>Contact Email</p>
                            <p>{leads?.contact_email}</p>
                        </div>

                        <div className={'mb-4'}>
                            <p className={'block font-bold mb-2'}>City</p>
                            <p>{leads?.city}</p>
                        </div>
                    </div>

                    <FormField label='Address' hasTextareaHeight>
                        <textarea className={'w-full'} disabled value={leads?.address} />
                    </FormField>

                    {leads.messages_lead && leads.messages_lead.length > 0 && (
                    <>
                        <p className={'block font-bold mb-2 mt-8'}>Message History</p>
                        <CardBox
                        className='mb-6 border border-gray-300 rounded overflow-hidden shadow-sm'
                        hasTable
                        >
                            <div className='overflow-x-auto'>
                                <table className="w-full text-left">
                                <thead>
                                <tr className="bg-gray-50 border-b border-gray-200 text-xs uppercase text-gray-500 font-semibold">
                                    <th className="px-4 py-3">Body</th>
                                    <th className="px-4 py-3">Read At</th>
                                    <th className="px-4 py-3">Date</th>
                                </tr>
                                </thead>
                                <tbody className="divide-y divide-gray-200">
                                {leads.messages_lead.map((item: any) => (
                                    <tr key={item.id} className="hover:bg-gray-50 cursor-pointer transition-colors" onClick={() => router.push(`/messages/messages-view/?id=${item.id}`)}>
                                        <td className="px-4 py-3" data-label="body">
                                            { item.body }
                                        </td>
                                        <td className="px-4 py-3" data-label="read_at">
                                            { dataFormatter.dateTimeFormatter(item.read_at) }
                                        </td>
                                        <td className="px-4 py-3" data-label="created_at_ts">
                                            { dataFormatter.dateTimeFormatter(item.created_at_ts) }
                                        </td>
                                    </tr>
                                ))}
                                </tbody>
                            </table>
                            </div>
                        </CardBox>
                    </>
                    )}

                    <BaseDivider />

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

            {activeTab === 'photos' && (
                <CardBox>
                    <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                        {leads.lead_photos_lead?.length > 0 ? (
                            leads.lead_photos_lead.map((photo: any) => (
                                <div key={photo.id} className="border border-gray-200 rounded p-2">
                                    <ImageField value={photo.photos} />
                                </div>
                            ))
                        ) : (
                            <p className="text-gray-500 italic">No photos available.</p>
                        )}
                    </div>
                </CardBox>
            )}

            {activeTab === 'matches' && (
                <CardBox hasTable>
                    <div className='overflow-x-auto'>
                        <table className="w-full text-left">
                            <thead>
                                <tr className="bg-gray-50 border-b border-gray-200 text-xs uppercase text-gray-500 font-semibold">
                                    <th className="px-4 py-3">Business</th>
                                    <th className="px-4 py-3">Status</th>
                                    <th className="px-4 py-3">Matched At</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-gray-200">
                                {leads.lead_matches_lead?.length > 0 ? (
                                    leads.lead_matches_lead.map((match: any) => (
                                        <tr key={match.id} className="hover:bg-gray-50 transition-colors">
                                            <td className="px-4 py-3">{match.business?.name}</td>
                                            <td className="px-4 py-3">{match.status}</td>
                                            <td className="px-4 py-3">{dataFormatter.dateTimeFormatter(match.created_at_ts)}</td>
                                        </tr>
                                    ))
                                ) : (
                                    <tr>
                                        <td colSpan={3} className="px-4 py-8 text-center text-gray-500 italic">No matches found.</td>
                                    </tr>
                                )}
                            </tbody>
                        </table>
                    </div>
                </CardBox>
            )}

            {activeTab === 'events' && (
                <CardBox hasTable>
                    <div className='overflow-x-auto'>
                        <table className="w-full text-left">
                            <thead>
                                <tr className="bg-gray-50 border-b border-gray-200 text-xs uppercase text-gray-500 font-semibold">
                                    <th className="px-4 py-3">Event Type</th>
                                    <th className="px-4 py-3">Actor</th>
                                    <th className="px-4 py-3">Notes</th>
                                    <th className="px-4 py-3">Date</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-gray-200">
                                {leads.lead_events_lead?.length > 0 ? (
                                    leads.lead_events_lead.map((event: any) => (
                                        <tr key={event.id} className="hover:bg-gray-50 transition-colors">
                                            <td className="px-4 py-3">{event.event_type}</td>
                                            <td className="px-4 py-3">{event.actor_user?.firstName}</td>
                                            <td className="px-4 py-3">{event.notes}</td>
                                            <td className="px-4 py-3">{dataFormatter.dateTimeFormatter(event.created_at_ts)}</td>
                                        </tr>
                                    ))
                                ) : (
                                    <tr>
                                        <td colSpan={4} className="px-4 py-8 text-center text-gray-500 italic">No events found.</td>
                                    </tr>
                                )}
                            </tbody>
                        </table>
                    </div>
                </CardBox>
            )}

          </SectionMain>
      </>
    );
};

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

export default LeadsView;
