'use client';

import Image from 'next/image';
import { Avatar } from '@/components/ui/avatar';
import { Badge } from '@/components/ui/badge';
import { Title, Text } from '@/components/ui/text';
import Table from '@/components/ui/table';
import { siteConfig } from '@/config/site.config';
import { useSelector, useDispatch } from 'react-redux';
import { useEffect } from 'react';
import { postDownloadInvoice } from '@/redux/slices/user/invoice/invoiceSlice';
import { useRouter, useSearchParams } from 'next/navigation';
import Link from 'next/link';
import { Button } from 'rizzui';
import { FaArrowLeft } from 'react-icons/fa';
import { routes } from '@/config/routes';
import { getSingleClientinvoice } from '@/redux/slices/user/client/invoice/clientinvoiceSlice';
import Spinner from '@/components/ui/spinner';
import { IoMdDownload } from "react-icons/io";
import moment from 'moment';
import withRoleAuth from '@/AuthGuard/withRoleAuth';
import { roles } from '@/config/roles';
import { CustomePageHeader } from '@/components/pageheader/pageheader';
import PageHeader from '@/app/shared/page-header';
import { capitalizeFirstLetter } from '@/utils/common-functions';

function InvoiceDetails({ params }: { params: { id: string } }) {

    const dispatch = useDispatch();
    const router = useRouter();

    const { singleInvoicedetails, loading } = useSelector((state: any) => state?.root?.clieninvoice);
    const IncoiceLoader = useSelector((state: any) => state?.root?.invoice)?.loading
    const { defaultWorkSpace } = useSelector((state: any) => state?.root?.workspace)
    // console.log(singleInvoicedetails, 'singleInvoicedetails')

    const data = singleInvoicedetails?.data?.[0];

    useEffect(() => {
        dispatch(getSingleClientinvoice(params?.id));
    }, [params?.id]);

    const columns = [
        {
            title: <p className='text-left text-[16px] font-bold'>Item Descriptions</p>,
            key: 'item',
            width: 600,
            render: (product: any, record: any, index: any) => (
                <>

                    {!(record.key === 'totalRow') ? <div className='poppins_font_number'>
                        <Title as="h6" className="mb-0.5 text-sm font-medium poppins_font_number">
                            {product?.item && product?.item != '' ? product?.item : "-"}
                        </Title>
                        <Text
                            as="p"
                            className="mb-0.5 text-sm break-all poppins_font_number"
                        >
                            {product?.description && product?.description != '' ? product?.description : "-"}
                        </Text>
                    </div> :
                        <Title as="h6" className="text-sm font-medium text-right">

                        </Title>}
                </>
            ),
        },
        {
            title: <p className='text-center text-[16px] font-bold'>Quantity</p>,
            key: 'qty',
            width: 150,
            render: (product: any, record: any, index: any) => (
                <>
                    {!(record.key === 'totalRow') ? <Title as="h6" className="mb-0.5 text-sm font-medium text-center poppins_font_number">
                        {product?.qty && product?.qty != '' ? product?.qty : "-"}
                    </Title> :
                        <Title as="h6" className="text-sm font-medium text-right">

                        </Title>}
                </>
            ),
        },
        {
            title: <p className='text-center text-[16px] font-bold'>Rate</p>,
            key: 'rate',
            width: 150,
            render: (product: any, record: any, index: any) => (
                <>
                    {!(record.key === 'totalRow') ? <Title as="h6" className="mb-0.5 text-sm font-medium text-center poppins_font_number">
                        {product?.rate && product?.rate != '' ? data?.currency_symbol + " " + product?.rate : "-"}
                    </Title> :
                        <Title as="h6" className="text-sm font-medium text-right">

                        </Title>}
                </>
            ),
        },
        {
            title: <p className='text-center text-[16px] font-bold'>Taxes</p>,
            key: 'tax',
            width: 200,
            render: (product: any, record: any, index: any) => (
                <>

                    {!(record.key === 'totalRow') ? <Title as="h6" className="mb-0.5 text-sm font-medium text-center poppins_font_number">
                        {product?.tax && product?.tax != '' ? product?.tax + " %" : "-"}
                    </Title> :
                        <Title className="text-[16px] text-[#8C80D2] font-bold text-right">
                            Total Amount :
                        </Title>}

                </>
            ),
        },
        {
            title: <p className='text-center text-[16px] font-bold'>Amount</p>,
            key: 'amount',
            width: 200,
            render: (product: any, record: any, index: any) => (
                // console.log(product, 'product'),
                <>

                    {!(record.key === 'totalRow') ? <Title as="h6" className="mb-0.5 text-sm font-medium text-center poppins_font_number">
                        {product?.amount && product?.amount != '' ? data?.currency_symbol + " " + product?.amount : "-"}
                    </Title> :
                        <div className=''>
                            <Title className="text-[16px] text-[#8C80D2] poppins_font_number font-bold text-center poppins_font_number">
                                {data?.currency_symbol} {data?.total && data?.total != '' ? data?.total : 0}
                            </Title>
                        </div>}
                </>
            ),
        }
    ];

    // Add an empty object and total row to the data
    const dataWithAdditionalRows = [...(Array.isArray(data?.invoice_content) ? data.invoice_content : []), { key: 'totalRow' }];

    function InvoiceDetailsListTable() {
        return (
            <Table
                data={dataWithAdditionalRows}
                columns={columns}
                variant="minimal"
                rowKey={(record) => record.id}
                scroll={{ x: 1100 }}
                className="mb-4 invoice_table_view"
            />
        );
    }

    const DownloadInvoice = () => {
        dispatch(postDownloadInvoice({ invoice_id: params?.id }))
    };

    return (
        <>
            {loading ? <div className='p-10 flex items-center justify-center'>
                <Spinner size="xl" tag='div' className='ms-3' />
            </div> : <>

                <CustomePageHeader titleClassName="montserrat_font_title" route={routes.invoice(defaultWorkSpace?.name)} title={data?.invoice_number && data?.invoice_number != "" ? data?.invoice_number : ""}>
                    <Button disabled={IncoiceLoader} onClick={DownloadInvoice} className="bg-[#8C80D2] text-white w-44 h-12 rounded-3xl text-sm">
                        Download Invoice
                    </Button>
                </CustomePageHeader>


                <div className="w-full bg-white rounded-xl border border-gray-200 p-5 text-sm sm:p-6 lg:p-4 2xl:p-10">
                    {/* creation date */}

                    <div className='grid grid-cols-1 gap-4 md:gap-3 md:grid-cols-2 lg:grid-cols-2 xl:grid-cols-5'>
                        <div className='flex  items-center ' >
                            <Text className="text-sm me-4 text-[#9BA1B9] ">Creation Date :</Text>
                            <Title className='poppins_font_number text-[#120425] text-sm '>{data?.createdAt ? moment(data?.createdAt).format('DD MMM, YYYY') : '-'}</Title>
                        </div>
                        <div className='flex  items-center '>
                            <Text className="text-sm me-4 text-[#9BA1B9]">Due Date :</Text>
                            <Title className='poppins_font_number text-[#120425] text-sm'>{data?.due_date ? moment(data?.due_date).format('DD MMM, YYYY') : '-'}</Title>

                        </div>
                        <div className='flex  items-center xl:col-span-2'>
                            <Text className="text-sm me-4 text-[#9BA1B9]">Invoice Number :</Text>
                            <Title className='text-[#120425] text-sm poppins_font_number'>{data?.invoice_number}</Title>

                        </div>
                        <div className='flex  items-center ' >
                            <Text className="text-sm me-4 text-[#9BA1B9] "> Payment Status </Text>
                            <Title className='text-[#120425] text-sm '> <Badge
                                variant="flat"
                                color={
                                    data?.status === 'draft'
                                        ? 'primary'
                                        : data?.status === 'paid'
                                            ? 'success'
                                            : data?.status === 'unpaid'
                                                ? 'warning'
                                                : data?.status === 'overdue'
                                                    ? 'danger'
                                                    : 'primary'
                                }
                                rounded="md"
                                className="capitalize"
                            >
                                {data?.status}
                            </Badge></Title>
                        </div>
                    </div>



                    <div className="my-4 grid gap-4 xs:grid-cols-2 sm:grid-cols-3 sm:grid-rows-1">
                        <div className="">
                            <Title className="mb-2 font-bold text-[20px] text-[#120425]">
                                From
                            </Title>


                                <Avatar src={`${process.env.NEXT_PUBLIC_API}/${data?.invoice_logo}`} name={data?.from?.agency_full_name ?? ''} className='h-[57px] w-[57px] text-white' />


                            <Text className="mb-2 mt-4 text-[24px] text-[#120425] font-bold uppercase poppins_font_number">
                                {data?.from?.agency_full_name && data?.from?.agency_full_name != '' && data?.from?.agency_full_name}
                            </Text>
                                <Text className="mb-2 text-[#9BA1B9] text-[16px] poppins_font_number"> {data?.from?.company_name && data?.from?.company_name != '' && data?.from?.company_name} </Text>
                            <Text className="mb-2 text-[16px] text-[#9BA1B9] poppins_font_number">
                                {data?.from?.address && data?.from?.address != '' && data?.from?.address + ","} <br /> {data?.from?.city?.name && data?.from?.city?.name != '' && data?.from?.city?.name + ","}
                                {data?.from?.state?.name && data?.from?.state?.name != '' && data?.from?.state?.name + ","} {data?.from?.country?.name && data?.from?.country?.name != '' && data?.from?.country?.name + ","}
                            </Text>
                                <Text className="poppins_font_number mb-4 text-[#9BA1B9] text-[16px]">{data?.from?.pincode && data?.from?.pincode != '' && data?.from?.pincode}</Text>

                            <div className='mb-4'>
                                    <Text className=" font-semibold text-[16px] text-[#9BA1B9]">
                                    Email Id
                                </Text>
                                <Text className=" text-[16px] montserrat_font_title font-semibold  text-[#8C80D2]">{data?.from?.email && data?.from?.email != '' ? data?.from?.email : "-"}  </Text>
                            </div>
                                <div className='mb-4'>
                                <Text className="font-semibold text-[16px] text-[#9BA1B9]">
                                    Phone
                                </Text>
                                    <Text className="poppins_font_number text-[16px] font-semibold  montserrat_font_title text-[#8C80D2]">{data?.from?.contact_number && data?.from?.contact_number != '' ? data?.from?.contact_number : "-"}</Text>
                            </div>
                        </div>
                        <div className="mt-4 xs:mt-0">
                            <Title className="mb-3 font-bold text-[20px] text-[#120425]">
                                Bill To
                            </Title>
                            <Text className="mb-2 text-[24px] text-[#120425] font-bold uppercase poppins_font_number">
                                {data?.custom_client?.name ? <div className='capitalize'> {data?.custom_client?.name}</div> : <div className='capitalize'>   {data?.to?.first_name && data?.to?.first_name != '' && data?.to?.first_name + " "}  {data?.to?.last_name && data?.to?.last_name != '' && data?.to?.last_name}</div>}
                            </Text>
                            <Text className="mb-2 text-[16px] text-[#9BA1B9] poppins_font_number">{data?.to?.company_name && data?.to?.company_name != '' && data?.to?.company_name}</Text>
                            <Text className="mb-2 text-[16px] text-[#9BA1B9] poppins_font_number">
                                {data?.custom_client?.address ? data.custom_client?.address : (
                                    <>
                                        {(data?.to?.address && data?.to?.address !== '') ? data?.to?.address + "," : data?.custom_client?.address}
                                        <br />
                                        {data?.to?.city?.name && data?.to?.city?.name !== '' && data?.to?.city?.name + ","}
                                        {data?.to?.state?.name && data?.to?.state?.name !== '' && data?.to?.state?.name + ","}
                                        {data?.to?.country?.name && data?.to?.country?.name !== '' && data?.to?.country?.name + ","}
                                    </>
                                )}
                            </Text>
                            <Text className="poppins_font_number mb-4 text-sm text-[#9BA1B9]">{data?.to?.pincode && data?.to?.pincode != '' && data?.to?.pincode}</Text>
                        </div>
                    </div>

                    <div className='table_border_remove'>
                        <InvoiceDetailsListTable />
                    </div>

                    {data?.memo && data?.memo != '' && <div className='flex justify-start flex-wrap items-baseline pb-3 border rounded-lg p-5 mt-2'>
                        <Text className="mb-1.5 break-all text-black poppins_font_number">{data?.memo && data?.memo != '' && data?.memo}</Text>
                    </div>}

                </div>
            </>}
        </>
    );
}

export default withRoleAuth([roles.agency, roles.teamAgency.team_agency], 'invoices', null, 'view')(InvoiceDetails);