'use client';
import axios from 'axios';
import { Metadata } from 'next';
import Link from 'next/link';
import React, { useEffect, useState } from 'react';
import IconTrashLines from '../icon/icon-trash-lines';
import IconPencil from '../icon/icon-pencil';
import Swal from 'sweetalert2';
import { useRouter } from 'next/navigation';
import { buildApiUrl } from '@/utils/BaseUrl.utils';

export const metadata: Metadata = {
    title: 'Knowledge Base',
};

const ListOfEvents = () => {
    const router = useRouter()

    const [events, setEvents] = useState([])

    useEffect(() => {
        getEvents()
    }, [])

    const getEvents = async () => {
        try {
            const eventRes: any = await axios?.get(buildApiUrl('events'))
            console.log("eventRes", eventRes)
            setEvents(eventRes?.data?.data)
        } catch (error) {
            console.log("error", error)
        }
    }

    const handleEdit = (event: any) => {
        // Redirect to edit page or open modal
        console.log("Edit", event);
        router.push(`/edit-event?event=${event.id}`);
    };

    // const handleDelete = async (event: any) => {
    //     const confirmed = confirm(`Are you sure you want to delete ${event.eventtitle}?`);
    //     if (!confirmed) return;

    //     try {
    //         await axios.delete(`https://api.tamilculturewaterloo.org/api/events/${event.id}`);
    //         getEvents(); // Refresh the list
    //     } catch (err) {
    //         console.error("Delete error", err);
    //     }
    // };

    const showAlert = async (event: any) => {
        Swal.fire({
            icon: 'warning',
            title: 'Are you sure?',
            text: "You won't be able to revert this!",
            showCancelButton: true,
            confirmButtonText: 'Delete',
            padding: '2em',
            customClass: { popup: 'sweet-alerts' },
        }).then(async (result) => {
            if (result.isConfirmed) {
                try {
                    await axios.delete(buildApiUrl(`events/${event.id}`));
                    Swal.fire({
                        title: 'Deleted!',
                        text: 'Your file has been deleted.',
                        icon: 'success',
                        customClass: { popup: 'sweet-alerts' },
                    });
                    getEvents(); // Refresh the list
                } catch (error) {
                    Swal.fire({
                        title: 'Error!',
                        text: 'Failed to delete the file.',
                        icon: 'error',
                        customClass: { popup: 'sweet-alerts' },
                    });
                }
            }
        });
    };

    return (
        <div>
            <div className="mt-10 container">
                <h3 className="mb-6 text-xl font-bold md:text-3xl">Events</h3>
                <div className="grid grid-cols-1 gap-5 sm:grid-cols-2 xl:grid-cols-4">
                    {/* ✅ First box: Create New Event */}
                    <Link href="/create-event" className="flex items-center justify-center space-y-5 rounded-md border border-dashed border-blue-500 bg-blue-50 p-5 text-center shadow hover:bg-blue-100 transition dark:border-blue-800 dark:bg-blue-900 dark:hover:bg-blue-800">
                        <div>
                            <div className="mb-3 text-5xl text-blue-600 dark:text-white">+</div>
                            <h5 className="text-lg font-semibold text-blue-800 dark:text-white">Create New Event</h5>
                        </div>
                    </Link>

                    {/* ✅ List dynamic or static event cards */}
                    {events.map((event: any, index) => (
                        <div
                            key={index}
                            className="relative rounded-md border border-white-light bg-white p-5 shadow-[0px_0px_2px_0px_rgba(145,158,171,0.20),0px_12px_24px_-4px_rgba(145,158,171,0.12)] dark:border-[#1B2E4B] dark:bg-black"
                        >
                            {/* Top-right edit/delete buttons */}
                            <div className="absolute top-5 right-5 flex gap-2 ">
                                <button onClick={() => handleEdit(event)} className="bg-blue-600 text-white text-xs px-2 py-1 rounded">
                                    <IconPencil />
                                </button>
                                <button
                                    onClick={() => showAlert(event)}
                                    // onClick={() => handleDelete(event)} 
                                    className="bg-red-600 text-white text-xs px-2 py-1 rounded">
                                    <IconTrashLines />
                                </button>
                            </div>

                            {/* Image */}
                            <div className="max-h-56 overflow-hidden rounded-md mt-0">
                                <img
                                    src={event.eventimageurl}
                                    alt={event.eventtitle}
                                    className="w-full object-cover"
                                />
                            </div>

                            {/* Event content */}
                            <div className="flex-1 mt-3">
                                <h4 className="text-xl mb-1.5 font-semibold dark:text-white">
                                    <Link href={`/event-gallery?eventid=${event?.id}`}>
                                        {event.eventtitle}
                                    </Link></h4>
                                <p>Date: {event.eventdate}</p>
                            </div>
                        </div>
                    ))}
                </div>

            </div>

        </div>
    );
};

export default ListOfEvents;
