import React, { useContext, useEffect, useState } from 'react'
import { ConfigContext } from '../Context/ConfigContext'
import axios from 'axios'
import Swal from 'sweetalert2'
import { TableRows, NoRecords } from '../Components/Shimmer'
import { DateFormaterMonth } from '../Components/GlobalFunctions'
import { Link } from 'react-router-dom'

const Archives = () => {
    const { apiHeaderJson, apiURL } = useContext(ConfigContext)
    const headers = apiHeaderJson

    const [data, setData] = useState([])
    const [next, setNext] = useState(false);
    const [prev, setPrev] = useState(false);
    const [page, setPage] = useState(1);
    const [limit] = useState(10);
    const [totalRecords, setTotalRecords] = useState(0);
    const [totalPages, setTotalPages] = useState(0);
    const [loading, setLoading] = useState(true)
    const [keyword, setKeyword] = useState('')
    const [errors, setErrors] = useState({})

    const GetList = async () => {
        try {
            setLoading(true);
            const response = await axios.get(`${apiURL}api/projects`, {
                headers: headers,
                params: {
                    page,
                    limit,
                    keyword
                }
            })

            if (response.data.success) {
                const filteredData = response.data.data.filter(project => project.project_status === 1);
                setData(filteredData);
                setNext(response.data.next);
                setPrev(response.data.prev);
                setTotalRecords(response.data.total_records);
                setTotalPages(response.data.total_pages);
            }
        } catch (error) {
            console.log(error);
        } finally {
            setLoading(false);
        }
    };

    const handlePrev = () => {
        if (prev) {
            setPage((prevPage) => prevPage - 1);
        }
    };

    const handleNext = () => {
        if (next) {
            setPage((prevPage) => prevPage + 1);
        }
    };

    const handleChange = (e) => {
        setPage(parseInt(e.target.value, 10));
    };

    useEffect(() => {
        const delayDebounce = setTimeout(() => {
            GetList();
        }, 500);

        return () => clearTimeout(delayDebounce);
    }, [page, limit, keyword]);


    return (
        <div className="main-content">
            <div className="page-content">
                <div className="container-fluid">
                    {/* start page title */}
                    <div className="row">
                        <div className="col-12">
                            <div className="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 className="mb-sm-0">Archives</h4>
                                <div className="page-title-right">
                                    <ol className="breadcrumb m-0">
                                        <li className="breadcrumb-item">
                                            <a>Dashboard</a>
                                        </li>
                                        <li className="breadcrumb-item active">Archives</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>
                    {/* end page title */}
                    <div className="row">
                        <div className="col-md-12">
                            <div className="card">
                                <div className="card-header" style={{ background: "#000000" }}>
                                    <div className="row d-flex align-items-center">
                                        <div className="col-md-7">
                                            <h4 className='text-white mb-0'>Archives List</h4>
                                        </div>
                                        {/* <div className="col-md-5">
                                            <div className="position-relative">
                                                <input
                                                    type="text"
                                                    className="form-control pe-4"
                                                    placeholder="Search by Project name"
                                                    name='keyword'
                                                    value={keyword}
                                                    onChange={(e) => setKeyword(e.target.value)}
                                                />
                                                <span className="position-absolute end-0 top-50 translate-middle-y me-3">
                                                    <i className="ri-search-line"></i>
                                                </span>
                                            </div>
                                        </div> */}
                                    </div>
                                </div>

                                <div className="card-body">
                                    <div className="table-responsive table-card">
                                        <table className="table table-bordered table-striped table-hover table-nowrap mb-0">
                                            {loading ? (
                                                <TableRows rows="10" colspan="6" />
                                            ) : (
                                                <>
                                                    <thead className="table-light text-center">
                                                        <tr>
                                                            <th>Project Name</th>
                                                            <th>Location</th>
                                                            <th>Start Date</th>
                                                            <th>End Date</th>
                                                            <th>Status</th>
                                                            <th>Action</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        {data.length > 0 ? (
                                                            data.map((row) => (
                                                                <tr key={row.project_id} className="text-center">
                                                                    <td className="text-center">
                                                                        <Link to={`/ProjectProfile/${row?.project_id}`}>{row?.project_title}</Link>
                                                                    </td>
                                                                    <td className="text-center">{row?.project_address}</td>

                                                                    <td className="text-center">{DateFormaterMonth(row?.project_start_date)}</td>
                                                                    <td className="text-center">{DateFormaterMonth(row?.project_end_date)}</td>
                                                                    <td className="text-center">
                                                                        {row.project_status === 1 ? <span className='badge bg-success-subtle text-success'>Completed</span> : "N/A"}
                                                                    </td>
                                                                    <td className="text-center">
                                                                        <Link
                                                                            to={`/PreviewProject/${row.project_id}`}
                                                                            className="btn btn-sm btn-info btn-label left"
                                                                        >
                                                                            <i className="ri-eye-line align-middle label-icon" />
                                                                            View
                                                                        </Link>
                                                                    </td>
                                                                </tr>
                                                            ))
                                                        ) : (
                                                            <tr>
                                                                <td colSpan={6}>
                                                                    <NoRecords />
                                                                </td>
                                                            </tr>
                                                        )}
                                                    </tbody>
                                                    {/* <tfoot className='table-light'>
                                                        <tr>
                                                            <th colSpan={6}>
                                                                <div className="d-flex justify-content-between">
                                                                    <button disabled={!prev && !loading} type="button" onClick={handlePrev} className={`btn btn-warning btn-label waves-effect waves-light`}>
                                                                        <i className="ri-arrow-left-line label-icon align-middle fs-16 me-2" /> Previous
                                                                    </button>
                                                                    <div className='col-md-4' style={{ display: 'flex', alignItems: 'center' }}>
                                                                        <small>Total Records: {totalRecords} | Total Pages: {totalPages} | Current Page: {page}</small>
                                                                    </div>
                                                                    <div className='col-md-2'>
                                                                        <select className="form-select" onChange={handleChange} value={page}>
                                                                            {Array.from({ length: totalPages }, (_, i) => (
                                                                                <option key={i + 1} value={i + 1}>
                                                                                    {i + 1}
                                                                                </option>
                                                                            ))}
                                                                        </select>
                                                                    </div>
                                                                    <button disabled={!next && !loading} type="button" onClick={handleNext} className={`btn btn-primary btn-label waves-effect right waves-light`}>
                                                                        Next <i className="ri-arrow-right-line label-icon align-middle fs-16 ms-2" />
                                                                    </button>
                                                                </div>
                                                            </th>
                                                        </tr>
                                                    </tfoot> */}
                                                </>
                                            )}
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    )
}

export default Archives