import DataTables from "../../components/DataTables";
import Dropdown from "../../components/Dropdown";
import IconHorizontalDots from "../../components/Icon/IconHorizontalDots";
import IconPencil from "../../components/Icon/IconPencil";
import IconTrashLines from "../../components/Icon/IconTrashLines";
import { useRef, useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import { Link } from "react-router-dom";
import Button from "../../components/Buttons";
import IconPlus from "../../components/Icon/IconPlus";
import AddShiftTime from "../../modals/settings/shift_time/AddShiftTime";
import EditShiftTime from "../../modals/settings/shift_time/EditShiftTime";
import DeleteModal from "../../modals/settings/DeleteModal";
import CustomSwitch from "../../components/CustomSwitch";
import api from '../../api/axios';
import { toast } from 'react-toastify';

interface ShiftTimeType {
    id: number;
    name: string;
    start_time: string;
    end_time: string;
    description: string | null;
    status: number;
    created_at?: string;
    updated_at?: string;
}

function ShiftTime() {
    const [shiftTimes, setShiftTimes] = useState<ShiftTimeType[]>([]);
    const [loading, setLoading] = useState(false);
    const [open, setOpen] = useState(false);
    const [editOpen, setEditOpen] = useState(false);
    const [editData, setEditData] = useState<ShiftTimeType | null>(null);
    const [editId, setEditId] = useState<number | null>(null);
    const [deleteOpen, setDeleteOpen] = useState(false);
    const [deleteRow, setDeleteRow] = useState<ShiftTimeType | null>(null);

    // Fetch shift times on component mount
    useEffect(() => {
        fetchShiftTimes();
    }, []);


    const fetchShiftTimes = async () => {
        setLoading(true);
        try {
            const response = await api.get('/shift_times/list');
            if (response.data.status === true) {
                const data = response.data.data || [];
                setShiftTimes(data);
            } else {
                toast.error(response.data.message || 'Failed to fetch shift times');
            }
        } catch (error: any) {
            console.error('Error fetching shift times:', error);
            toast.error(error.response?.data?.message || 'Failed to fetch shift times');
        } finally {
            setLoading(false);
        }
    };

    const handleAddShiftTime = async (data: any) => {
        try {
            const response = await api.post('/shift_times/add', {
                name: data.name,
                start_time: data.start_time,
                end_time: data.end_time,
                description: data.description || null,
            });

            if (response.data.status === true) {
                toast.success(response.data.message || 'Shift time added successfully');
                fetchShiftTimes(); // Refresh the list
                setOpen(false);
            } else {
                toast.error(response.data.message || 'Failed to add shift time');
            }
        } catch (error: any) {
            console.error('Error adding shift time:', error);
            if (error.response?.data?.errors) {
                const errors = error.response.data.errors;
                Object.keys(errors).forEach(key => {
                    toast.error(`${key}: ${errors[key][0]}`);
                });
            } else {
                toast.error(error.response?.data?.message || 'Failed to add shift time');
            }
        }
    };

    const handleEditShiftTime = async (data: any) => {
        try {
            const response = await api.post('/shift_times/update', {
                id: editId,
                name: data.name,
                start_time: data.start_time,
                end_time: data.end_time,
                description: data.description || null,
            });

            if (response.data.status === true) {
                toast.success(response.data.message || 'Shift time updated successfully');
                fetchShiftTimes(); // Refresh the list
                setEditOpen(false);
                setEditData(null);
                setEditId(null);
            } else {
                toast.error(response.data.message || 'Failed to update shift time');
            }
        } catch (error: any) {
            console.error('Error updating shift time:', error);
            if (error.response?.data?.errors) {
                const errors = error.response.data.errors;
                Object.keys(errors).forEach(key => {
                    toast.error(`${key}: ${errors[key][0]}`);
                });
            } else {
                toast.error(error.response?.data?.message || 'Failed to update shift time');
            }
        }
    };

    const handleDeleteShiftTime = async () => {
        if (!deleteRow) return;

        try {
            const response = await api.delete(`/shift_times/delete/${deleteRow.id}`);
            if (response.data.status === true) {
                toast.success(response.data.message || 'Shift time deleted successfully');
                fetchShiftTimes(); // Refresh the list
                setDeleteOpen(false);
                setDeleteRow(null);
            } else {
                toast.error(response.data.message || 'Failed to delete shift time');
            }
        } catch (error: any) {
            console.error('Error deleting shift time:', error);
            toast.error(error.response?.data?.message || 'Failed to delete shift time');
        }
    };

    const handleToggleStatus = async (id: number, checked: boolean) => {
        const newStatus = checked ? 0 : 1;
        try {
            const response = await api.put(`/shift_times/status/${id}`, {
                status: newStatus
            });

            if (response.data.status === true) {
                toast.success(`Shift time ${checked ? 'activated' : 'deactivated'} successfully`);
                // Update local state
                setShiftTimes(prevTimes =>
                    prevTimes.map(shift =>
                        shift.id === id ? { ...shift, status: newStatus } : shift
                    )
                );
            } else {
                toast.error(response.data.message || 'Failed to update status');
                // Revert the toggle by refreshing data
                fetchShiftTimes();
            }
        } catch (error: any) {
            console.error('Error updating status:', error);
            toast.error(error.response?.data?.message || 'Failed to update status');
            // Revert the toggle by refreshing data
            fetchShiftTimes();
        }
    };

    const formatTimeForDisplay = (timeString: string) => {
        if (!timeString) return '-';
        // Convert 24-hour format to 12-hour format
        const [hours, minutes] = timeString.split(':');
        const hour = parseInt(hours);
        const ampm = hour >= 12 ? 'PM' : 'AM';
        const hour12 = hour % 12 || 12;
        return `${hour12}:${minutes} ${ampm}`;
    };

    const shiftTimeColumns = [
        {
            accessor: 'name',
            title: 'Shift Time',
            render: (row: ShiftTimeType) => (
                <div className="flex items-center gap-3">
                    <div className="text-sm font-semibold">{row.name}</div>
                </div>
            ),
        },
        {
            accessor: 'start_time',
            title: 'Shift Start Time',
            render: (row: ShiftTimeType) => (
                <div className="flex items-center gap-3">
                    <span className="w-2 h-2 rounded-full bg-green-500"></span>
                    <div className="text-sm">{formatTimeForDisplay(row.start_time)}</div>
                </div>
            ),
        },
        {
            accessor: 'end_time',
            title: 'Shift End Time',
            render: (row: ShiftTimeType) => (
                <div className="flex items-center gap-3">
                    <span className="w-2 h-2 rounded-full bg-red-500"></span>
                    <div className="text-sm">{formatTimeForDisplay(row.end_time)}</div>
                </div>
            ),
        },
        {
            accessor: 'description',
            title: 'Description',
            render: (row: ShiftTimeType) => (
                <div className="flex items-center gap-3">
                    <div className="text-sm">{row.description || '-'}</div>
                </div>
            ),
        },
        {
            accessor: "status",
            title: "Status",
            render: (row: ShiftTimeType) => (
                <CustomSwitch
                    key={row.id}
                    id={`switch-${row.id}`}
                    checked={row.status === 0}
                    onChange={(checked) => handleToggleStatus(row.id, checked)}
                />
            ),
        },
        {
            accessor: 'actions',
            title: 'Actions',
            render: (row: ShiftTimeType) => (
                <Dropdown
                    btnClassName="cursor-pointer"
                    placement="bottom-start"
                    button={<IconHorizontalDots />}
                >
                    <ul className="text-dark dark:text-white-dark !py-0 dark:text-white-light/90">
                        <li
                            className="hover:bg-rose-700 hover:text-white cursor-pointer"
                            onMouseDown={(e) => {
                                e.preventDefault();
                                setEditData(row);
                                setEditId(row.id);
                                setEditOpen(true);
                            }}
                        >
                            <div className="flex gap-4 items-center px-3 py-2">
                                <IconPencil />
                                <span className="text-base fw-semibold">Edit</span>
                            </div>
                        </li>
                        <li
                            className="hover:bg-rose-700 hover:text-white cursor-pointer"
                            onMouseDown={(e) => {
                                e.preventDefault();
                                setDeleteRow(row);
                                setDeleteOpen(true);
                            }}
                        >
                            <div className="flex gap-4 items-center px-3 py-2">
                                <IconTrashLines />
                                <span className="text-base fw-semibold">Delete</span>
                            </div>
                        </li>
                    </ul>
                </Dropdown>
            ),
        }
    ];

    return (
        <>
            <div className="flex items-center justify-between">
                <ul className="flex space-x-2 items-center">
                    <li>
                        <Link to="/shift-time-settings" className="text-primary text-lg hover:underline">
                            Shift Time
                        </Link>
                    </li>
                    <li className="before:content-['/'] ml-2">
                        <span>Settings</span>
                    </li>
                </ul>
                <Button
                    icon={<IconPlus />}
                    iconPosition="left"
                    onClick={() => setOpen(true)}
                >
                    Add Shift Time
                </Button>
            </div>
            <div className="pt-4">
                <div className="p-4 rounded-xl shadow-md bg-white w-full max-w-full overflow-hidden">
                    <div className="grid grid-cols-12">
                        <div className="col-span-12">
                            {loading ? (
                                <div className="flex justify-center items-center py-8">
                                    <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
                                    <span className="ml-2">Loading shift times...</span>
                                </div>
                            ) : (
                                <DataTables
                                    data={shiftTimes}
                                    columns={shiftTimeColumns}
                                />
                            )}
                        </div>
                    </div>
                </div>
            </div>

            <AddShiftTime
                open={open}
                onClose={() => setOpen(false)}
                onSave={handleAddShiftTime}
            />

            <EditShiftTime
                open={editOpen}
                onClose={() => {
                    setEditOpen(false);
                    setEditData(null);
                    setEditId(null);
                }}
                onSave={handleEditShiftTime}
                data={editData}
                id={editId}
            />

            <DeleteModal
                open={deleteOpen}
                title="Delete Shift Time"
                message={`Are you sure you want to delete "${deleteRow?.name}"? This action cannot be undone.`}
                onClose={() => {
                    setDeleteOpen(false);
                    setDeleteRow(null);
                }}
                onConfirm={handleDeleteShiftTime}
            />
        </>
    );
}

export default ShiftTime;
