
"use client";

import { useState } from "react";
import { format, addDays, startOfWeek, endOfWeek, subWeeks, addWeeks } from "date-fns";
import { type Employee } from "@/lib/types";
import { getShiftForEmployee } from "@/lib/data-helpers";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { ChevronLeft, ChevronRight, Shuffle } from "lucide-react";
import { SwapShiftDialog } from "./swap-shift-dialog";

type Translation = {
    previousWeek: string;
    nextWeek: string;
    swapShifts: string;
    swapTitle: string;
    swapDescription: string;
    employee1: string;
    employee2: string;
    confirmSwap: string;
    noEmployees: string;
    firstShift: string;
    secondShift: string;
    unassigned: string;
}

type ShiftOverrides = { [date: string]: { [employeeId: string]: 'first' | 'second' | 'none' } };

export default function ShiftCalendar({ employees, t, shiftOverrides }: { employees: Employee[], t: Translation, shiftOverrides: ShiftOverrides }) {
    const [currentDate, setCurrentDate] = useState(new Date());
    const [isDialogOpen, setIsDialogOpen] = useState(false);
    const [selectedDate, setSelectedDate] = useState<Date | null>(null);

    const weekStartsOn = 1; // Monday
    const weekStart = startOfWeek(currentDate, { weekStartsOn });
    const weekEnd = endOfWeek(currentDate, { weekStartsOn });

    const days = Array.from({ length: 7 }, (_, i) => addDays(weekStart, i));

    const handlePrevWeek = () => setCurrentDate(subWeeks(currentDate, 1));
    const handleNextWeek = () => setCurrentDate(addWeeks(currentDate, 1));
    
    const openSwapDialog = (date: Date) => {
        setSelectedDate(date);
        setIsDialogOpen(true);
    };

    return (
        <div>
             <div className="flex justify-center items-center gap-4 mb-6">
                <Button variant="outline" size="icon" onClick={handlePrevWeek} aria-label={t.previousWeek}>
                    <ChevronLeft className="h-4 w-4" />
                </Button>
                <h2 className="text-xl font-bold text-center">
                    {format(weekStart, "MMM d, yyyy")} - {format(weekEnd, "MMM d, yyyy")}
                </h2>
                <Button variant="outline" size="icon" onClick={handleNextWeek} aria-label={t.nextWeek}>
                    <ChevronRight className="h-4 w-4" />
                </Button>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 xl:grid-cols-7 gap-4 items-start">
                {days.map(day => {
                    const firstShiftEmployees = employees.filter(e => getShiftForEmployee(e, day, shiftOverrides) === 'first');
                    const secondShiftEmployees = employees.filter(e => getShiftForEmployee(e, day, shiftOverrides) === 'second');

                    return (
                        <Card key={day.toString()} className="flex flex-col h-full">
                            <CardHeader className="pb-4">
                                <CardTitle className="text-base text-center">{format(day, "EEE")}</CardTitle>
                                <CardDescription className="text-center">{format(day, "MMM d")}</CardDescription>
                            </CardHeader>
                            <CardContent className="flex-grow space-y-4">
                                <div>
                                    <h4 className="font-semibold text-sm mb-2 border-b pb-1">{t.firstShift}</h4>
                                    {firstShiftEmployees.length > 0 ? (
                                        <ul className="space-y-1">
                                            {firstShiftEmployees.map(e => <li key={e.id} className="text-xs p-1 bg-blue-50 rounded-md">{e.name}</li>)}
                                        </ul>
                                    ): <p className="text-xs text-muted-foreground">{t.unassigned}</p>}
                                </div>
                                <div>
                                    <h4 className="font-semibold text-sm mb-2 border-b pb-1">{t.secondShift}</h4>
                                     {secondShiftEmployees.length > 0 ? (
                                        <ul className="space-y-1">
                                            {secondShiftEmployees.map(e => <li key={e.id} className="text-xs p-1 bg-amber-50 rounded-md">{e.name}</li>)}
                                        </ul>
                                    ): <p className="text-xs text-muted-foreground">{t.unassigned}</p>}
                                </div>
                            </CardContent>
                            <div className="p-4 pt-0 mt-auto">
                                <Button variant="ghost" size="sm" className="w-full" onClick={() => openSwapDialog(day)}>
                                    <Shuffle className="w-4 h-4 me-2"/>
                                    {t.swapShifts}
                                </Button>
                            </div>
                        </Card>
                    );
                })}
            </div>
             {selectedDate && (
                <SwapShiftDialog
                    isOpen={isDialogOpen}
                    onClose={() => setIsDialogOpen(false)}
                    date={selectedDate}
                    employees={employees}
                    t={t}
                />
            )}
        </div>
    );
}
