'use client';

import React, { useMemo, useState } from "react";
import {
    addMonths,
    subMonths,
    startOfMonth,
    endOfMonth,
    startOfWeek,
    endOfWeek,
    addDays,
    isSameMonth,
    isSameDay,
    format,
    parseISO,
    isAfter,
} from "date-fns";
import { FaChevronLeft, FaChevronRight, FaCalendarPlus, FaClock, FaMapMarkerAlt, FaRegCalendarAlt } from "react-icons/fa";
import { motion, AnimatePresence } from "framer-motion";
import {
    Container,
    Box,
    Flex,
    Grid,
    GridItem,
    Heading,
    Text,
    Button,
    IconButton,
    Badge,
    VStack,
    HStack,
    Input,
} from "@chakra-ui/react";

// --- Demo Data ---
const demoEvents = [
    { id: "1", title: "Dogodek 1", start: new Date().toISOString(), color: "blue.500" },
    { id: "2", title: "Dogodek 2", start: addDays(new Date(), 2).toISOString(), color: "pink.500" },
    { id: "3", title: "Dogodek 3", start: addDays(new Date(), 6).toISOString(), color: "green.500" },
    { id: "4", title: "Dogodek 4", start: addDays(new Date(), 12).toISOString(), color: "orange.500" },
];

// --- Helpers ---
const getMonthMatrix = (current) => {
    const monthStart = startOfMonth(current);
    const monthEnd = endOfMonth(current);
    const startDate = startOfWeek(monthStart, { weekStartsOn: 1 }); // Monday
    const endDate = endOfWeek(monthEnd, { weekStartsOn: 1 });

    const rows = [];
    let day = startDate;
    let row = [];

    while (day <= endDate) {
        for (let i = 0; i < 7; i++) {
            row.push(day);
            day = addDays(day, 1);
        }
        rows.push(row);
        row = [];
    }

    return rows;
};

const DayBadge = ({ count }) =>
    count > 0 ? (
        <Badge ml={1} fontSize="0.6rem" colorScheme="purple" variant="subtle" borderRadius="full" px={2} py={0.5}>
            {count}
        </Badge>
    ) : null;

const EventPill = ({ ev }) => (
    <HStack spacing={2} px={2} py={1} borderRadius="xl" bg={ev.color ?? "gray.500"} color="white" _hover={{ opacity: 0.9 }}>
        <Text fontSize="xs" noOfLines={1} fontWeight="medium">
            {ev.title}
        </Text>
    </HStack>
);

// --- Main Component (Plain JS, Chakra v1/v2 compatible) ---
export default function Calendar({ initialDate, initialEvents = demoEvents }) {
    // Static tokens (works without Chakra hooks)
    const mutedColor = "gray.600";
    const tileBg = "white";
    const tileBgMuted = "gray.50";
    const selectedRing = "purple.400";

    const [currentDate, setCurrentDate] = useState(
        initialDate ? (typeof initialDate === "string" ? parseISO(initialDate) : initialDate) : new Date()
    );
    const [selectedDate, setSelectedDate] = useState(new Date());
    const [events, setEvents] = useState(initialEvents);

    const monthMatrix = useMemo(() => getMonthMatrix(currentDate), [currentDate]);

    const eventsByDay = useMemo(() => {
        const map = new Map();
        events.forEach((ev) => {
            const d = format(parseISO(ev.start), "yyyy-MM-dd");
            if (!map.has(d)) map.set(d, []);
            map.get(d).push(ev);
        });
        return map;
    }, [events]);

    const todayKey = format(new Date(), "yyyy-MM-dd");

    const upcomingEvents = useMemo(() => {
        const now = new Date();
        return [...events]
            .filter((e) => isAfter(parseISO(e.start), addDays(now, -1)))
            .sort((a, b) => parseISO(a.start).getTime() - parseISO(b.start).getTime());
    }, [events]);

    // Quick add form state
    const [newTitle, setNewTitle] = useState("");
    const [newDate, setNewDate] = useState(format(new Date(), "yyyy-MM-dd"));
    const [newTime, setNewTime] = useState("09:00");
    const [newLocation, setNewLocation] = useState("");

    const addEvent = () => {
        if (!newTitle.trim()) return;
        const dt = new Date(`${newDate}T${newTime}:00`);
        setEvents((prev) => [
            ...prev,
            {
                id: typeof crypto !== "undefined" && crypto.randomUUID ? crypto.randomUUID() : String(Date.now()),
                title: newTitle.trim(),
                start: dt.toISOString(),
                location: newLocation.trim() || undefined,
                color: "purple.500",
            },
        ]);
        setNewTitle("");
        setNewLocation("");
    };

    return (
        <Container>
            <Box maxW="6xl" mx="auto" p={{base: 4, md: 8}}>
                <Flex mb={6} direction={{base: "column", sm: "row"}} gap={3} align={{sm: "center"}}
                      justify="space-between">
                    <HStack spacing={2}>
                        <Heading size="4xl" as="h2">
                            Prihajajoči dogodki
                        </Heading>
                        <FaRegCalendarAlt size={20}/>
                    </HStack>
                    <HStack spacing={2}>
                        <Button variant="outline" size="sm" onClick={() => setCurrentDate(new Date())}>
                            Danes
                        </Button>
                        <HStack spacing={1} borderWidth="1px" borderRadius="2xl" p={1}>
                            <IconButton aria-label="Prejšnji mesec" variant="ghost" size="sm"
                                        onClick={() => setCurrentDate((d) => subMonths(d, 1))}>
                                <FaChevronLeft/>
                            </IconButton>
                            <Text px={3} fontSize="sm" fontWeight="medium" minW="140px" textAlign="center">
                                {format(currentDate, "MMMM yyyy")}
                            </Text>
                            <IconButton aria-label="Naslednji mesec" variant="ghost" size="sm"
                                        onClick={() => setCurrentDate((d) => addMonths(d, 1))}>
                                <FaChevronRight/>
                            </IconButton>
                        </HStack>
                    </HStack>
                </Flex>

                <Grid templateColumns={{base: "1fr", lg: "2fr 1fr"}} gap={6}>
                    {/* Calendar Grid */}
                    <Box borderWidth="1px" borderRadius="2xl" overflow="hidden">
                        <Box pb={0} borderBottomWidth="1px" px={4}>
                            <Grid templateColumns="repeat(7, 1fr)" color={mutedColor} fontSize="xs" fontWeight="medium">
                                {["Pon", "Tor", "Sre", "Čet", "Pet", "Sob", "Ned"].map((d) => (
                                    <GridItem key={d} px={2} py={3} textAlign="center">
                                        {d}
                                    </GridItem>
                                ))}
                            </Grid>
                        </Box>
                        <Box pt={2} px={4}>
                            <Grid templateColumns="repeat(7, 1fr)" gap={1}>
                                {monthMatrix.flat().map((day, idx) => {
                                    const inMonth = isSameMonth(day, currentDate);
                                    const key = format(day, "yyyy-MM-dd");
                                    const isToday = key === todayKey;
                                    const isSelected = selectedDate && isSameDay(day, selectedDate);
                                    const dayEvents = eventsByDay.get(key) || [];

                                    return (
                                        <Box
                                            as="button"
                                            key={idx}
                                            onClick={() => setSelectedDate(day)}
                                            h="96px"
                                            p={2}
                                            borderRadius="2xl"
                                            bg={inMonth ? tileBg : tileBgMuted}
                                            color={inMonth ? undefined : mutedColor}
                                            borderWidth={isSelected ? "2px" : "0px"}
                                            borderColor={isSelected ? selectedRing : "transparent"}
                                        >
                                            <Flex align="center">
                                                <HStack>
                                                    <Flex
                                                        align="center"
                                                        justify="center"
                                                        h={6}
                                                        w={6}
                                                        borderRadius="full"
                                                        fontSize="xs"
                                                        fontWeight="semibold"
                                                        bg={isToday ? "purple.500" : "transparent"}
                                                        color={isToday ? "white" : undefined}
                                                    >
                                                        {format(day, "d")}
                                                    </Flex>
                                                    <DayBadge count={dayEvents.length}/>
                                                </HStack>
                                            </Flex>

                                            <VStack mt={2} align="stretch" spacing={1} maxH="56px" overflow="hidden">
                                                <AnimatePresence initial={false}>
                                                    {dayEvents.slice(0, 3).map((ev) => (
                                                        <motion.div key={ev.id} initial={{opacity: 0, y: -6}}
                                                                    animate={{opacity: 1, y: 0}}
                                                                    exit={{opacity: 0, y: 6}}>
                                                            <EventPill ev={ev}/>
                                                        </motion.div>
                                                    ))}
                                                </AnimatePresence>
                                                {dayEvents.length > 3 && (
                                                    <Text fontSize="xs" color={mutedColor} noOfLines={1}>
                                                        +{dayEvents.length - 3} more
                                                    </Text>
                                                )}
                                            </VStack>
                                        </Box>
                                    );
                                })}
                            </Grid>

                            {/* Selected Day Drawer */}
                            <AnimatePresence>
                                {selectedDate && (
                                    <motion.div initial={{opacity: 0, y: 10}} animate={{opacity: 1, y: 0}}
                                                exit={{opacity: 0, y: 10}}>
                                        <Box mt={4} borderWidth="1px" borderRadius="2xl" p={4}>
                                            <Text fontSize="sm" color={mutedColor}>
                                                Na izbran dan
                                            </Text>
                                            <Text fontSize="md" fontWeight="medium">
                                                {format(selectedDate, "EEEE, MMM d")}
                                            </Text>
                                            <VStack align="stretch" spacing={2} mt={2}>
                                                {(eventsByDay.get(format(selectedDate, "yyyy-MM-dd")) || []).length === 0 ? (
                                                    <Text fontSize="sm" color={mutedColor}>
                                                        No events for this day.
                                                    </Text>
                                                ) : (
                                                    (eventsByDay.get(format(selectedDate, "yyyy-MM-dd")) || []).map((ev) => (
                                                        <HStack key={ev.id} align="start" spacing={3} borderWidth="1px"
                                                                borderRadius="xl" p={3}>
                                                            <Box mt={0.5} h={2.5} w={2.5} borderRadius="full"
                                                                 bg={ev.color ?? "gray.400"}/>
                                                            <Box flex="1">
                                                                <Text fontWeight="medium" noOfLines={2}>
                                                                    {ev.title}
                                                                </Text>
                                                                <HStack mt={1} spacing={3} wrap="wrap"
                                                                        color={mutedColor} fontSize="xs">
                                                                    <HStack spacing={1}>
                                                                        <FaClock/>
                                                                        <Text>{format(parseISO(ev.start), "EEE, MMM d HH:mm")}</Text>
                                                                    </HStack>
                                                                    {ev.location && (
                                                                        <HStack spacing={1}>
                                                                            <FaMapMarkerAlt/>
                                                                            <Text>{ev.location}</Text>
                                                                        </HStack>
                                                                    )}
                                                                </HStack>
                                                            </Box>
                                                        </HStack>
                                                    ))
                                                )}
                                            </VStack>
                                        </Box>
                                    </motion.div>
                                )}
                            </AnimatePresence>
                        </Box>
                    </Box>

                    {/* Sidebar */}
                    <VStack spacing={6} align="stretch">
                        {/* Quick add
                        <Box borderWidth="1px" borderRadius="2xl">
                            <Box pb={0} borderBottomWidth="1px" px={4} py={3}>
                                <Heading as="h3" size="sm">
                                    Quick add event
                                </Heading>
                            </Box>
                            <Box pt={4} px={4} pb={4}>
                                <VStack spacing={3} align="stretch">
                                    <Box>
                                        <Text as="label" htmlFor="title" fontSize="sm" fontWeight="medium" mb={1} display="block">Title</Text>
                                        <Input id="title" value={newTitle} onChange={(e) => setNewTitle(e.target.value)} />
                                    </Box>
                                    <Grid templateColumns="repeat(2, 1fr)" gap={3}>
                                        <Box>
                                            <Text as="label" htmlFor="date" fontSize="sm" fontWeight="medium" mb={1} display="block">Date</Text>
                                            <Input id="date" type="date" value={newDate} onChange={(e) => setNewDate(e.target.value)} />
                                        </Box>
                                        <Box>
                                            <Text as="label" htmlFor="time" fontSize="sm" fontWeight="medium" mb={1} display="block">Time</Text>
                                            <Input id="time" type="time" value={newTime} onChange={(e) => setNewTime(e.target.value)} />
                                        </Box>
                                    </Grid>
                                    <Box>
                                        <Text as="label" htmlFor="location" fontSize="sm" fontWeight="medium" mb={1} display="block">Location</Text>
                                        <Input id="location" value={newLocation} onChange={(e) => setNewLocation(e.target.value)} />
                                    </Box>
                                    <Button onClick={addEvent} leftIcon={<FaCalendarPlus />} colorScheme="purple" alignSelf="flex-start">
                                        Add
                                    </Button>
                                </VStack>
                            </Box>
                        </Box>*/}

                        {/* Upcoming */}
                        <Box h="520px" borderWidth="1px" borderRadius="2xl" overflow="hidden">
                            <Box pb={0} borderBottomWidth="1px" px={4} py={3}>
                                <Heading as="h3" size="sm">
                                    Prihajajoči dogodki
                                </Heading>
                            </Box>
                            <Box pt={3} px={4} h="full" overflowY="auto" pr={3} pb={4}>
                                <VStack spacing={3} align="stretch">
                                    {upcomingEvents.length === 0 ? (
                                        <Text fontSize="sm" color={mutedColor}>
                                            Trenutno prihodnjih dogodkov.
                                        </Text>
                                    ) : (
                                        upcomingEvents.map((ev) => (
                                            <HStack key={ev.id} align="start" spacing={3} borderWidth="1px"
                                                    borderRadius="xl" p={3}>
                                                <Box mt={0.5} h={2.5} w={2.5} borderRadius="full"
                                                     bg={ev.color ?? "gray.400"}/>
                                                <Box flex="1" minW={0}>
                                                    <Text fontWeight="medium" noOfLines={1}>
                                                        {ev.title}
                                                    </Text>
                                                    <HStack mt={1} spacing={3} wrap="wrap" color={mutedColor}
                                                            fontSize="xs">
                                                        <HStack spacing={1}>
                                                            <FaClock/>
                                                            <Text>{format(parseISO(ev.start), "EEE, MMM d HH:mm")}</Text>
                                                        </HStack>
                                                        {ev.location && (
                                                            <HStack spacing={1}>
                                                                <FaMapMarkerAlt/>
                                                                <Text>{ev.location}</Text>
                                                            </HStack>
                                                        )}
                                                    </HStack>
                                                </Box>
                                            </HStack>
                                        ))
                                    )}
                                </VStack>
                            </Box>
                        </Box>
                    </VStack>
                </Grid>
            </Box>
        </Container>
    );
}
