import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { Head, router, useForm, usePage } from "@inertiajs/react";
import { useState, useEffect } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import {
    Calendar as CalendarIcon,
    Plus,
    Trash2,
    User as UserIcon,
    ChevronLeft,
    ChevronRight,
    Clock,
    Briefcase,
    CheckCircle2,
    AlertCircle,
    Timer,
    Edit3,
    AlertTriangle,
    X,
    Building2,
    Search,
} from "lucide-react";
import { CancelButton, ConfirmDeleteButton } from "@/Components/ui/action-buttons";
import SecondaryButton from "@/Components/SecondaryButton";
import { Button } from "@/components/ui/button";
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
    DialogFooter,
} from "@/components/ui/dialog";
import SearchableSelect from "@/Components/SearchableSelect";
import { cn } from "@/lib/utils";
import PlanTaskModal from "./Partials/PlanTaskModal";
import ContactSelectorModal from "@/Pages/Business/Contacts/Partials/ContactSelectorModal";
import StatusSwitcherModal from "./Partials/StatusSwitcherModal";
import useTranslation from "@/Hooks/useTranslation";
import useWorkLogListener from "@/Hooks/useWorkLogListener";

export default function Index({
    users,
    availableTasks,
    currentDate,
    canCreate,
    canDelete,
    canEdit,
    affaires,
    projects,
    allUsers,
    businessContacts = [],
}) {
    const [isAddModalOpen, setIsAddModalOpen] = useState(false);
    const [isEditModalOpen, setIsEditModalOpen] = useState(false);
    const [selectedUserId, setSelectedUserId] = useState(null);
    const [selectedProjectId, setSelectedProjectId] = useState("");
    const [selectedEditProjectId, setSelectedEditProjectId] = useState("");
    const [selectedPlanning, setSelectedPlanning] = useState(null);
    const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
    const [isContactSelectorOpen, setIsContactSelectorOpen] = useState(false);
    const [itemToDelete, setItemToDelete] = useState(null);
    const [isStatusSwitcherOpen, setIsStatusSwitcherOpen] = useState(false);
    const [selectedStatusPlanning, setSelectedStatusPlanning] = useState(null);
    const [now, setNow] = useState(new Date());
    const [searchTerm, setSearchTerm] = useState("");
    const { t } = useTranslation();
    const { statusTaskAssignments = [] } = usePage().props;

    const translateStatus = (statusName) => {
        if (!statusName) return "";
        const key = `status_task_assignments.${statusName.toLowerCase()}`;
        const translated = t(key);
        return translated === key ? statusName : translated;
    };

    const getContactName = (contact) => {
        if (!contact) return "";
        let first = contact.firstname || contact.name || "";
        let last = contact.lastname || "";
        let formattedName = first;
        if (last && last.toLowerCase() !== first.toLowerCase()) {
            formattedName += ` ${last}`;
        }
        if (contact.tier) {
            formattedName += ` @${contact.tier.name}`;
        }
        return `${contact.civility ? contact.civility + " " : ""}${formattedName}`.trim();
    };

    useEffect(() => {
        const interval = setInterval(() => setNow(new Date()), 1000);
        return () => clearInterval(interval);
    }, []);

    useWorkLogListener(null, ["users"]);

    const addForm = useForm({
        task_id: "",
        user_id: "",
        scheduled_date: currentDate,
        scheduled_dates: [currentDate],
        start_time: "",
        end_time: "",
        affaire_id: "",
        business_contact_id: "",
        business_tier_id: "",
    });

    useEffect(() => {
        addForm.setData((data) => ({
            ...data,
            scheduled_date: currentDate,
            scheduled_dates: [currentDate],
        }));
    }, [currentDate]);

    const editForm = useForm({
        task_id: "",
        user_id: "",
        scheduled_date: "",
        start_time: "",
        end_time: "",
        affaire_id: "",
        business_contact_id: "",
        business_tier_id: "",
        description: "",
        severity: "normal",
        status_task_assignment_id: "",
    });

    const filteredTasks = selectedProjectId
        ? availableTasks.filter(
              (t) => t.project_id === parseInt(selectedProjectId),
          )
        : availableTasks;

    const filteredEditTasks = selectedEditProjectId
        ? availableTasks.filter(
              (t) => t.project_id === parseInt(selectedEditProjectId),
          )
        : availableTasks;

    const filteredUsers = users.filter(user => {
        if (!searchTerm) return true;
        const searchLower = searchTerm.toLowerCase();
        
        if (user.name?.toLowerCase().includes(searchLower)) return true;
        
        return user.planning.some(item => {
            const taskTitle = item.task?.title?.toLowerCase() || "";
            const projectName = item.task?.project?.name?.toLowerCase() || "";
            const affaireTitle = item.affaire?.title?.toLowerCase() || "";
            
            const contact = item.business_contact || item.affaire?.business_contact || item.affaire?.businessContact || item.businessContact;
            const tier = item.business_tier || item.affaire?.business_tier || item.affaire?.businessTier || item.businessTier;
            
            const contactName = getContactName(contact).toLowerCase();
            const tierName = tier?.name?.toLowerCase() || "";

            return taskTitle.includes(searchLower) || 
                   projectName.includes(searchLower) || 
                   affaireTitle.includes(searchLower) || 
                   contactName.includes(searchLower) || 
                   tierName.includes(searchLower);
        });
    }).map(user => {
        if (!searchTerm) return user;
        const searchLower = searchTerm.toLowerCase();
        
        if (user.name?.toLowerCase().includes(searchLower)) return user;

        return {
            ...user,
            planning: user.planning.filter(item => {
                const taskTitle = item.task?.title?.toLowerCase() || "";
                const projectName = item.task?.project?.name?.toLowerCase() || "";
                const affaireTitle = item.affaire?.title?.toLowerCase() || "";
                
                const contact = item.business_contact || item.affaire?.business_contact || item.affaire?.businessContact || item.businessContact;
                const tier = item.business_tier || item.affaire?.business_tier || item.affaire?.businessTier || item.businessTier;
                
                const contactName = getContactName(contact).toLowerCase();
                const tierName = tier?.name?.toLowerCase() || "";

                return taskTitle.includes(searchLower) || 
                       projectName.includes(searchLower) || 
                       affaireTitle.includes(searchLower) || 
                       contactName.includes(searchLower) || 
                       tierName.includes(searchLower);
            })
        };
    });

    const handleDateChange = (newDate) => {
        router.get(
            route("planning.index"),
            { date: newDate },
            { preserveState: true },
        );
    };

    const formatDuration = (minutes) => {
        if (!minutes) return "0m";
        const h = Math.floor(minutes / 60);
        const m = minutes % 60;
        return h > 0 ? `${h}h ${m}m` : `${m}m`;
    };

    const getAssignmentActiveLog = (item, userId, allPlanningItems) => {
        const activeLogsForTask = item.task.work_logs?.filter((log) => !log.ended_at && log.user_id === userId) || [];
        if (activeLogsForTask.length === 0) return undefined;

        const activeLog = activeLogsForTask[0];

        // 1. Try exact match
        const isExactMatch = String(activeLog.affaire_id || '') === String(item.affaire_id || '') &&
                             String(activeLog.business_tier_id || '') === String(item.business_tier_id || '') &&
                             String(activeLog.business_contact_id || '') === String(item.business_contact_id || '');
        if (isExactMatch) return activeLog;

        // 2. Fallbacks if no exact match exists anywhere in planning
        const hasExactMatchInPlanning = allPlanningItems.some(p => 
            p.task_id === item.task_id &&
            String(p.affaire_id || '') === String(activeLog.affaire_id || '') &&
            String(p.business_tier_id || '') === String(activeLog.business_tier_id || '') &&
            String(p.business_contact_id || '') === String(activeLog.business_contact_id || '')
        );

        if (!hasExactMatchInPlanning) {
            // Is there any generic item?
            const genericItems = allPlanningItems.filter(p => p.task_id === item.task_id && !p.affaire_id && !p.business_tier_id && !p.business_contact_id);
            if (genericItems.length > 0) {
                const logDate = activeLog.started_at ? activeLog.started_at.split(' ')[0].split('T')[0] : '';
                let chosenGeneric = genericItems.find(p => p.scheduled_date === logDate);
                if (!chosenGeneric) chosenGeneric = genericItems[0];

                if (item === chosenGeneric) return activeLog;
                return undefined;
            }

            // If there's NO generic item either, just match the first item for this task
            const firstItemForTask = allPlanningItems.find(p => p.task_id === item.task_id);
            if (firstItemForTask === item) return activeLog;
        }

        return undefined;
    };

    const calculateLiveDuration = (item, userId, allPlanningItems) => {
        const activeLog = getAssignmentActiveLog(item, userId, allPlanningItems);
        if (!activeLog || !activeLog.started_at)
            return formatDuration(item.task.work_logs_sum_duration_minutes);

        let startedAtStr = activeLog.started_at.replace(" ", "T");
        if (!startedAtStr.includes("Z") && !startedAtStr.includes("+")) {
            startedAtStr += "Z";
        }

        const startTime = Date.parse(startedAtStr);
        if (isNaN(startTime))
            return formatDuration(item.task.work_logs_sum_duration_minutes);

        const diffMinutes = Math.floor((now.getTime() - startTime) / 60000);
        const finalDiff =
            diffMinutes > 0 && diffMinutes < 10080 ? diffMinutes : 0;

        const totalMinutes =
            (parseInt(item.task.work_logs_sum_duration_minutes) || 0) + finalDiff;
        return formatDuration(totalMinutes);
    };

    const nextDay = () => {
        const [year, month, day] = currentDate.split("-").map(Number);
        const date = new Date(year, month - 1, day);
        date.setDate(date.getDate() + 1);
        const y = date.getFullYear();
        const m = String(date.getMonth() + 1).padStart(2, "0");
        const d = String(date.getDate()).padStart(2, "0");
        handleDateChange(`${y}-${m}-${d}`);
    };

    const prevDay = () => {
        const [year, month, day] = currentDate.split("-").map(Number);
        const date = new Date(year, month - 1, day);
        date.setDate(date.getDate() - 1);
        const y = date.getFullYear();
        const m = String(date.getMonth() + 1).padStart(2, "0");
        const d = String(date.getDate()).padStart(2, "0");
        handleDateChange(`${y}-${m}-${d}`);
    };

    const openAddModal = (userId) => {
        setSelectedUserId(userId);
        addForm.setData("user_id", userId);
        setIsAddModalOpen(true);
    };

    const openEditModal = (planning) => {
        setSelectedPlanning(planning);

        // Ensure date is in YYYY-MM-DD format for the input
        let dateVal = planning.scheduled_date;
        if (dateVal && typeof dateVal === "string" && dateVal.includes("T")) {
            dateVal = dateVal.split("T")[0];
        }

        setSelectedEditProjectId(planning.task?.project_id ? String(planning.task.project_id) : "");

        editForm.setData({
            task_id: String(planning.task_id),
            user_id: String(planning.user_id),
            scheduled_date: dateVal,
            start_time: planning.start_time || "",
            end_time: planning.end_time || "",
            affaire_id: planning.affaire_id ? String(planning.affaire_id) : "",
            business_contact_id: planning.business_contact_id ? String(planning.business_contact_id) : "",
            business_tier_id: planning.business_tier_id ? String(planning.business_tier_id) : "",
            description: planning.description || "",
            severity: planning.severity || "normal",
            status_task_assignment_id: planning.status_task_assignment_id || "",
        });
        setIsEditModalOpen(true);
    };

    const submitAdd = (e) => {
        e.preventDefault();
        addForm.post(route("planning.store"), {
            onSuccess: () => {
                setIsAddModalOpen(false);
                addForm.reset();
            },
        });
    };

    const submitEdit = (e) => {
        e.preventDefault();
        editForm.put(route("planning.update", selectedPlanning.id), {
            onSuccess: () => {
                setIsEditModalOpen(false);
                editForm.reset();
            },
        });
    };

    const removePlanning = (id) => {
        setItemToDelete(id);
        setIsDeleteModalOpen(true);
    };

    const confirmDelete = () => {
        if (!itemToDelete) return;
        router.delete(route("planning.destroy", itemToDelete), {
            only: ["users"],
            preserveScroll: true,
            onSuccess: () => {
                setIsDeleteModalOpen(false);
                setItemToDelete(null);
            },
        });
    };

    return (
        <AuthenticatedLayout header={null}>
            <Head title={t('execution.team_planning.title')} />

            <div className="space-y-6">
                {/* Header & Date Switcher */}
                <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 bg-white dark:bg-slate-900 p-6 rounded-[2rem] shadow-sm border border-slate-200 dark:border-slate-800">
                    <div className="space-y-1">
                        <h1 className="text-2xl font-black tracking-tight text-slate-900 dark:text-white">
                            {t('execution.team_planning.title')}
                        </h1>
                        <p className="text-sm text-slate-500 font-medium">
                            {t('execution.team_planning.description')}
                        </p>
                    </div>

                    <div className="flex items-center gap-2 bg-slate-100 dark:bg-slate-800 p-1.5 rounded-2xl border border-slate-200 dark:border-slate-700">
                        <Button
                            variant="ghost"
                            size="icon"
                            onClick={prevDay}
                            className="rounded-xl hover:bg-white dark:hover:bg-slate-700"
                        >
                            <ChevronLeft className="size-4" />
                        </Button>

                        <div className="flex items-center gap-2 px-4 py-2 bg-white dark:bg-slate-900 rounded-xl shadow-sm border border-slate-200 dark:border-slate-700">
                            <CalendarIcon className="size-4 text-blue-500" />
                            <input
                                type="date"
                                value={currentDate}
                                onChange={(e) =>
                                    handleDateChange(e.target.value)
                                }
                                className="bg-transparent border-none p-0 text-sm font-black focus:ring-0 w-32"
                            />
                        </div>

                        <Button
                            variant="ghost"
                            size="icon"
                            onClick={nextDay}
                            className="rounded-xl hover:bg-white dark:hover:bg-slate-700"
                        >
                            <ChevronRight className="size-4" />
                        </Button>
                    </div>
                </div>

                {/* Search Bar */}
                <div className="relative w-full">
                    <Search className="absolute left-4 top-1/2 -translate-y-1/2 size-5 text-slate-400" />
                    <input
                        type="text"
                        placeholder={t("execution.my_planning.search", "Rechercher une tâche, projet, contact ou utilisateur...")}
                        value={searchTerm}
                        onChange={(e) => setSearchTerm(e.target.value)}
                        className="w-full pl-12 pr-4 py-3.5 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl text-sm font-medium focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-all outline-none shadow-sm"
                    />
                </div>

                {/* Users Grid */}
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                    {filteredUsers.map((user) => (
                        <Card
                            key={user.id}
                            className="border-none shadow-lg bg-white dark:bg-slate-900 overflow-hidden rounded-[2rem]"
                        >
                            <CardHeader className="border-b border-slate-100 dark:border-slate-800 pb-4">
                                <div className="flex items-center justify-between">
                                    <div className="flex items-center gap-3">
                                        <div className="size-10 rounded-2xl bg-blue-500/10 flex items-center justify-center text-blue-600 dark:text-blue-400">
                                            <UserIcon className="size-5" />
                                        </div>
                                        <div>
                                            <CardTitle className="text-base font-black">
                                                {user.name}
                                            </CardTitle>
                                            <p className="text-[10px] font-bold text-slate-500 uppercase tracking-widest">
                                                {user.teams
                                                    ?.map((t) => t.name)
                                                    .join(", ") || t('execution.team_planning.no_team')}
                                            </p>
                                        </div>
                                    </div>
                                    {canCreate && (
                                        <Button
                                            variant="ghost"
                                            size="icon"
                                            className="rounded-xl bg-slate-50 dark:bg-slate-800 hover:bg-blue-500 hover:text-white transition-all"
                                            onClick={() =>
                                                openAddModal(user.id)
                                            }
                                        >
                                            <Plus className="size-4" />
                                        </Button>
                                    )}
                                </div>
                            </CardHeader>
                            <CardContent className="p-4 space-y-3 min-h-[100px]">
                                {user.planning.length === 0 ? (
                                    <div className="flex flex-col items-center justify-center py-6 text-slate-400">
                                        <Clock className="size-8 opacity-20 mb-2" />
                                        <p className="text-xs font-bold uppercase tracking-wider">
                                            {t('execution.team_planning.no_tasks_planned')}
                                        </p>
                                    </div>
                                ) : (
                                    user.planning.map((item) => (
                                        <div
                                            key={item.id}
                                            className="group relative bg-slate-50 dark:bg-slate-800/50 hover:bg-slate-100 dark:hover:bg-slate-800 p-4 rounded-2xl border border-transparent hover:border-slate-200 dark:hover:border-slate-700 transition-all"
                                        >
                                            <div className="flex items-start justify-between gap-2">
                                                <div className="space-y-1 flex-1">
                                                    <div className="flex items-center gap-2">
                                                        <span
                                                             className={cn(
                                                                 "size-2 rounded-full",
                                                                 !(item.status_task_assignment || item.statusTaskAssignment)
                                                                     ? (item.status === "completed"
                                                                         ? "bg-emerald-500"
                                                                         : "bg-blue-500 animate-pulse")
                                                                     : ""
                                                             )}
                                                             style={(item.status_task_assignment || item.statusTaskAssignment) ? { backgroundColor: (item.status_task_assignment || item.statusTaskAssignment).color } : {}}
                                                         />
                                                        {item.severity === "urgent" && (
                                                            <span className="text-[8px] font-black uppercase px-1.5 py-0.5 rounded-md bg-red-600 text-white border border-red-600 shadow-md shadow-red-500/10 animate-pulse">
                                                                URGENT
                                                            </span>
                                                        )}
                                                         <h4 className="text-sm font-bold text-slate-900 dark:text-white leading-tight">
                                                             {item.task.title}
                                                         </h4>
                                                         <div
                                                             role="button"
                                                             onClick={(e) => {
                                                                 e.preventDefault();
                                                                 e.stopPropagation();
                                                                 setSelectedStatusPlanning(item);
                                                                 setIsStatusSwitcherOpen(true);
                                                             }}
                                                             className={cn(
                                                                 "px-2 py-0.5 rounded-full text-[8px] font-black uppercase tracking-widest border flex items-center gap-1 hover:scale-105 active:scale-95 transition-all cursor-pointer select-none",
                                                                 !(item.status_task_assignment || item.statusTaskAssignment)
                                                                     ? (item.status === "completed"
                                                                        ? "bg-emerald-500/10 text-emerald-600 border-emerald-500/20"
                                                                        : "bg-blue-500/10 text-blue-600 border-blue-500/20")
                                                                     : ""
                                                             )}
                                                             style={
                                                                 (item.status_task_assignment || item.statusTaskAssignment)
                                                                     ? {
                                                                           backgroundColor: `${(item.status_task_assignment || item.statusTaskAssignment).color}15`,
                                                                           color: (item.status_task_assignment || item.statusTaskAssignment).color,
                                                                           borderColor: `${(item.status_task_assignment || item.statusTaskAssignment).color}30`,
                                                                       }
                                                                     : {}
                                                             }
                                                         >
                                                             {translateStatus((item.status_task_assignment || item.statusTaskAssignment) ? (item.status_task_assignment || item.statusTaskAssignment).name : item.status)}
                                                         </div>
                                                    </div>
                                                    {(item.start_time ||
                                                        item.end_time) && (
                                                        <div className="flex items-center gap-1.5 text-[10px] font-black text-blue-600 dark:text-blue-400 bg-blue-500/5 px-2 py-0.5 rounded-md w-fit">
                                                            <Clock className="size-2.5" />
                                                            {item.start_time?.substring(
                                                                0,
                                                                5,
                                                            )}
                                                            {item.end_time &&
                                                                ` - ${item.end_time?.substring(0, 5)}`}
                                                        </div>
                                                    )}
                                                    <div className="flex flex-wrap items-center gap-x-3 gap-y-1">
                                                        <div className="flex items-center gap-1 text-[10px] font-bold text-slate-500 uppercase tracking-tight">
                                                            <Briefcase className="size-3" />
                                                            {
                                                                item.task
                                                                    .project
                                                                    ?.name
                                                            }
                                                        </div>
                                                        <div
                                                            className={cn(
                                                                "flex items-center gap-1 text-[10px] font-bold uppercase tracking-tight",
                                                                (() => {
                                                                    const activeLog = getAssignmentActiveLog(item, user.id, user.planning);
                                                                    if (!activeLog) return "text-blue-500";
                                                                    let startedAtStr = activeLog.started_at.replace(" ", "T");
                                                                    if (!startedAtStr.includes("Z") && !startedAtStr.includes("+")) {
                                                                        startedAtStr += "Z";
                                                                    }
                                                                    const startTime = Date.parse(startedAtStr);
                                                                    const isLongRunning = !isNaN(startTime) && (now.getTime() - startTime) / (1000 * 60 * 60) >= 8;
                                                                    return isLongRunning ? "text-amber-600 dark:text-amber-400 font-extrabold" : "text-rose-600";
                                                                })(),
                                                                getAssignmentActiveLog(item, user.id, user.planning) && "animate-pulse",
                                                            )}
                                                        >
                                                            {(() => {
                                                                const activeLog = getAssignmentActiveLog(item, user.id, user.planning);
                                                                if (!activeLog) {
                                                                    return (
                                                                        <>
                                                                            <Timer className="size-3" />
                                                                            {calculateLiveDuration(item, user.id, user.planning)}
                                                                        </>
                                                                    );
                                                                }
                                                                let startedAtStr = activeLog.started_at.replace(" ", "T");
                                                                if (!startedAtStr.includes("Z") && !startedAtStr.includes("+")) {
                                                                    startedAtStr += "Z";
                                                                }
                                                                const startTime = Date.parse(startedAtStr);
                                                                const isLongRunning = !isNaN(startTime) && (now.getTime() - startTime) / (1000 * 60 * 60) >= 8;

                                                                return (
                                                                    <>
                                                                        <Timer className={cn("size-3", !isLongRunning && "animate-spin-slow")} />
                                                                        {isLongRunning ? "⚠️ " : ""}{t('execution.team_planning.live') || 'Live'} {calculateLiveDuration(item, user.id, user.planning)}
                                                                    </>
                                                                );
                                                            })()}
                                                        </div>
                                                        {item.affaire && (
                                                            <div className="px-2 py-0.5 bg-blue-500/10 text-blue-600 dark:text-blue-400 rounded-md text-[9px] font-black uppercase tracking-widest">
                                                                {item.affaire.title}
                                                            </div>
                                                        )}
                                                        {(() => {
                                                            const contact = item.business_contact || item.affaire?.business_contact || item.affaire?.businessContact || item.businessContact;
                                                            const tier = item.business_tier || item.affaire?.business_tier || item.affaire?.businessTier || item.businessTier;
                                                            const contactObj = contact || tier;

                                                            if (!contactObj) return null;

                                                            return (
                                                                <div className="flex items-center gap-1.5 px-2 py-1 mt-0.5 bg-indigo-50 dark:bg-indigo-900/20 border border-indigo-100 dark:border-indigo-800/30 rounded-lg w-full max-w-fit">
                                                                    <div className="flex items-center gap-1.5">
                                                                        {contact ? <UserIcon className="size-3 text-indigo-500" /> : <Building2 className="size-3 text-indigo-500" />}
                                                                        <span className="text-[10px] font-black text-indigo-700 dark:text-indigo-300 truncate max-w-[150px]">
                                                                            {contact 
                                                                                ? getContactName(contact)
                                                                                : tier?.name}
                                                                        </span>
                                                                    </div>
                                                                    {/* Role Badges */}
                                                                    <div className="flex items-center gap-0.5 pl-1.5 border-l border-indigo-200 dark:border-indigo-800/50">
                                                                        {tier?.is_client && (
                                                                            <span className="w-3.5 h-3.5 rounded bg-blue-100 dark:bg-blue-900/40 text-blue-700 dark:text-blue-400 text-[8px] font-black flex items-center justify-center" title={t('execution.team_planning.client_title')}>
                                                                                {t('execution.team_planning.client')}
                                                                            </span>
                                                                        )}
                                                                        {tier?.is_prospect && (
                                                                            <span className="w-3.5 h-3.5 rounded bg-purple-100 dark:bg-purple-900/40 text-purple-700 dark:text-purple-400 text-[8px] font-black flex items-center justify-center" title={t('execution.team_planning.prospect_title')}>
                                                                                {t('execution.team_planning.prospect')}
                                                                            </span>
                                                                        )}
                                                                        {tier?.is_supplier && (
                                                                            <span className="w-3.5 h-3.5 rounded bg-amber-100 dark:bg-amber-900/40 text-amber-700 dark:text-amber-400 text-[8px] font-black flex items-center justify-center" title={t('execution.team_planning.supplier_title')}>
                                                                                {t('execution.team_planning.supplier')}
                                                                            </span>
                                                                        )}
                                                                        {(tier && !tier.is_client && !tier.is_prospect && !tier.is_supplier) && (
                                                                            <span className="w-3.5 h-3.5 rounded bg-green-100 dark:bg-green-900/40 text-green-700 dark:text-green-400 text-[8px] font-black flex items-center justify-center" title={t('execution.team_planning.other_title')}>
                                                                                {t('execution.team_planning.other')}
                                                                            </span>
                                                                        )}
                                                                        {contact && (
                                                                            <span className="w-3.5 h-3.5 rounded bg-slate-200 dark:bg-slate-800 text-slate-700 dark:text-slate-300 text-[8px] font-black flex items-center justify-center" title={t('execution.team_planning.contact_person_title')}>
                                                                                {t('execution.team_planning.contact_person')}
                                                                            </span>
                                                                        )}
                                                                    </div>
                                                                </div>
                                                            );
                                                        })()}
                                                      </div>
                                                      {item.description && (
                                                          <div className="mt-3 p-3 bg-slate-50 dark:bg-slate-800/50 rounded-xl border border-slate-100 dark:border-slate-800 w-full">
                                                              <p className="text-xs font-medium text-slate-500 dark:text-slate-400 leading-relaxed italic">
                                                                  {item.description}
                                                              </p>
                                                          </div>
                                                      )}
                                                  </div>

                                                  <div className="flex items-center gap-1">
                                                    {canEdit && (
                                                        <button
                                                            onClick={() =>
                                                                openEditModal(
                                                                    item,
                                                                )
                                                            }
                                                            className="opacity-0 group-hover:opacity-100 p-1.5 rounded-lg text-slate-400 hover:text-blue-500 hover:bg-blue-50 dark:hover:bg-blue-500/10 transition-all"
                                                        >
                                                            <Edit3 className="size-3.5" />
                                                        </button>
                                                    )}
                                                    {canDelete && (
                                                        <button
                                                            onClick={() =>
                                                                removePlanning(
                                                                    item.id,
                                                                )
                                                            }
                                                            className="opacity-0 group-hover:opacity-100 p-1.5 rounded-lg text-slate-400 hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-500/10 transition-all"
                                                        >
                                                            <Trash2 className="size-3.5" />
                                                        </button>
                                                    )}
                                                </div>
                                            </div>
                                        </div>
                                    ))
                                )}
                            </CardContent>
                        </Card>
                    ))}
                </div>
            </div>

            <PlanTaskModal
                show={isAddModalOpen}
                onClose={() => setIsAddModalOpen(false)}
                users={allUsers || users || []}
                projects={projects}
                affaires={affaires}
                businessContacts={businessContacts}
                availableTasks={availableTasks}
                currentDate={currentDate}
                userId={selectedUserId}
                hideAssignToUser={false}
            />

            {/* Edit Task Modal */}
            <Dialog open={isEditModalOpen} onOpenChange={setIsEditModalOpen}>
                <DialogContent 
                    className="w-full sm:max-w-xl md:max-w-2xl lg:max-w-4xl xl:max-w-5xl rounded-[2rem] bg-white dark:bg-slate-900 p-8 max-h-[90vh] overflow-y-auto"
                    onInteractOutside={(e) => {
                        if (isContactSelectorOpen) e.preventDefault();
                    }}
                >
                    <DialogHeader>
                        <DialogTitle className="text-2xl font-black tracking-tight text-slate-900 dark:text-white">
                            {t('execution.team_planning.edit_planning', { title: selectedPlanning?.task.title })}
                        </DialogTitle>
                    </DialogHeader>

                    <form onSubmit={submitEdit} className="space-y-6 pt-4">
                        <div className="space-y-2">
                            <label className="text-[10px] font-black text-slate-500 uppercase tracking-[0.2em]">
                                {t('execution.team_planning.select_project')}
                            </label>
                            <SearchableSelect
                                options={projects.map((p) => ({
                                    value: p.id,
                                    label: p.name,
                                }))}
                                value={selectedEditProjectId}
                                onChange={(val) => {
                                    setSelectedEditProjectId(val);
                                    editForm.setData("task_id", "");
                                }}
                                placeholder={t('execution.team_planning.filter_tasks_by_project')}
                            />
                        </div>

                        <div className="space-y-2">
                            <label className="text-[10px] font-black text-slate-500 uppercase tracking-[0.2em]">
                                {t('execution.team_planning.select_task')}
                            </label>
                            <SearchableSelect
                                options={filteredEditTasks.map((t) => ({
                                    value: t.id,
                                    label: t.title,
                                    subLabel: t.project?.name,
                                }))}
                                value={editForm.data.task_id}
                                onChange={(val) => {
                                    editForm.setData("task_id", val);
                                }}
                                placeholder={
                                    selectedEditProjectId
                                        ? t('execution.team_planning.choose_a_task')
                                        : t('execution.team_planning.please_select_project_first')
                                }
                                disabled={!selectedEditProjectId}
                            />
                            {editForm.errors.task_id && (
                                <p className="text-red-500 text-xs font-bold">
                                    {editForm.errors.task_id}
                                </p>
                            )}
                        </div>

                        <div className="space-y-2">
                            <label className="text-[10px] font-black text-slate-500 uppercase tracking-[0.2em]">
                                {t('execution.team_planning.assign_to')}
                            </label>
                            <SearchableSelect
                                options={allUsers.map((u) => ({
                                    value: u.id,
                                    label: u.name,
                                }))}
                                value={editForm.data.user_id}
                                onChange={(val) =>
                                    editForm.setData("user_id", val)
                                }
                                placeholder={t('execution.team_planning.reassign_task')}
                            />
                            {editForm.errors.user_id && (
                                <p className="text-red-500 text-xs font-bold">
                                    {editForm.errors.user_id}
                                </p>
                            )}
                        </div>

                        <div className="space-y-2">
                            <label className="text-[10px] font-black text-slate-500 uppercase tracking-[0.2em]">
                                {t('execution.team_planning.scheduled_date')}
                            </label>
                            <input
                                type="date"
                                value={editForm.data.scheduled_date}
                                onChange={(e) =>
                                    editForm.setData(
                                        "scheduled_date",
                                        e.target.value,
                                    )
                                }
                                className="w-full bg-slate-50 dark:bg-slate-800 border-slate-200 dark:border-slate-700 rounded-xl text-sm font-bold focus:ring-blue-500 text-slate-900 dark:text-white"
                            />
                            {editForm.errors.scheduled_date && (
                                <p className="text-red-500 text-xs font-bold">
                                    {editForm.errors.scheduled_date}
                                </p>
                            )}
                        </div>

                        <div className="space-y-2">
                            <label className="text-[10px] font-black text-slate-500 uppercase tracking-[0.2em]">
                                {t('execution.team_planning.affaire_optional')}
                            </label>
                            <SearchableSelect
                                options={affaires.map((a) => ({
                                    value: a.id,
                                    label: `${a.business_tier?.name || ""} - ${a.title}`,
                                }))}
                                value={editForm.data.affaire_id}
                                onChange={(val) => {
                                    editForm.setData({
                                        ...editForm.data,
                                        affaire_id: val,
                                        business_contact_id: val ? "" : editForm.data.business_contact_id,
                                        business_tier_id: val ? "" : editForm.data.business_tier_id
                                    });
                                }}
                                placeholder={t('execution.team_planning.link_to_affaire')}
                            />
                        </div>

                        <div className="space-y-2">
                            <label className="text-[10px] font-black text-slate-500 uppercase tracking-[0.2em]">
                                {t('execution.team_planning.select_contact_optional')} / TIER
                            </label>
                            
                            {(editForm.data.business_contact_id || editForm.data.business_tier_id) ? (
                                <div className="flex items-center justify-between p-3 bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-xl">
                                    <div className="flex items-center gap-3">
                                        <div className="size-8 rounded-lg bg-blue-50 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400 flex items-center justify-center shrink-0">
                                            {businessContacts.find(c => (editForm.data.business_tier_id && c.is_tier && String(c.id) === String(editForm.data.business_tier_id)) || (editForm.data.business_contact_id && !c.is_tier && String(c.id) === String(editForm.data.business_contact_id)))?.type === "contact" ? <UserIcon className="size-4" /> : <Building2 className="size-4" />}
                                        </div>
                                        <div className="flex flex-col">
                                            <span className="text-sm font-black text-slate-900 dark:text-white line-clamp-1">
                                                {(() => {
                                                    const sc = businessContacts.find(c => (editForm.data.business_tier_id && c.is_tier && String(c.id) === String(editForm.data.business_tier_id)) || (editForm.data.business_contact_id && !c.is_tier && String(c.id) === String(editForm.data.business_contact_id)));
                                                    if (!sc) return "";
                                                    if (sc.is_tier) return sc.name;
                                                    let first = sc.firstname || sc.name || "";
                                                    let last = sc.lastname || "";
                                                    let formattedName = first;
                                                    if (last && last.toLowerCase() !== first.toLowerCase()) {
                                                        formattedName += ` ${last}`;
                                                    }
                                                    if (sc.company_name) {
                                                        formattedName += ` @${sc.company_name}`;
                                                    }
                                                    return `${sc.civility ? sc.civility + " " : ""}${formattedName}`.trim();
                                                })()}
                                            </span>
                                        </div>
                                    </div>
                                    <div className="flex items-center gap-2">
                                        <Button
                                            type="button"
                                            variant="outline"
                                            size="sm"
                                            onClick={() => setIsContactSelectorOpen(true)}
                                            className="h-8 text-xs font-bold text-slate-700 dark:text-slate-300 hover:text-slate-900 dark:hover:text-white"
                                        >
                                            {t('execution.team_planning.change')}
                                        </Button>
                                        <Button
                                            type="button"
                                            variant="ghost"
                                            size="sm"
                                            onClick={() => {
                                                editForm.setData({
                                                    ...editForm.data,
                                                    business_contact_id: "",
                                                    business_tier_id: "",
                                                });
                                            }}
                                            className="h-8 w-8 p-0 text-slate-400 hover:text-red-500 rounded-lg"
                                        >
                                            <X className="size-4" />
                                        </Button>
                                    </div>
                                </div>
                            ) : (
                                <Button
                                    type="button"
                                    variant="outline"
                                    onClick={() => setIsContactSelectorOpen(true)}
                                    className="w-full justify-start text-slate-500 bg-white dark:bg-slate-950 border-slate-200 dark:border-slate-800 hover:bg-slate-50 dark:hover:bg-slate-900 font-bold"
                                >
                                    <Search className="size-4 mr-2" />
                                    {t('execution.team_planning.browse_contacts')}
                                </Button>
                            )}
                        </div>

                        <div className="grid grid-cols-2 gap-4">
                            <div className="space-y-2 col-span-2">
                                <label className="text-[10px] font-black text-slate-500 uppercase tracking-[0.2em]">
                                    {t('execution.team_planning.description_optional')}
                                </label>
                                <textarea
                                    value={editForm.data.description}
                                    onChange={(e) => editForm.setData("description", e.target.value)}
                                    placeholder={t('execution.team_planning.description_placeholder')}
                                    className="w-full bg-slate-50 dark:bg-slate-800 border-slate-200 dark:border-slate-700 rounded-xl text-sm font-bold focus:ring-blue-500 text-slate-900 dark:text-white resize-none h-20"
                                />
                                {editForm.errors.description && (
                                    <p className="text-red-500 text-xs font-bold mt-1">
                                        {editForm.errors.description}
                                    </p>
                                )}
                            </div>

                            <div className="flex items-center gap-2.5 py-1 col-span-2">
                                <input
                                    type="checkbox"
                                    id="urgent-checkbox-inline-edit"
                                    checked={editForm.data.severity === "urgent"}
                                    onChange={(e) => editForm.setData("severity", e.target.checked ? "urgent" : "normal")}
                                    className="rounded-lg border-slate-200 dark:border-slate-700 text-blue-600 focus:ring-blue-500 size-4.5 dark:bg-slate-800"
                                    name="severity"
                                />
                                <label
                                    htmlFor="urgent-checkbox-inline-edit"
                                    className="text-[10px] font-black text-slate-500 dark:text-slate-400 uppercase tracking-[0.2em] cursor-pointer select-none"
                                >
                                    Urgent / High Priority
                                </label>
                            </div>

                            <div className="space-y-2">
                                <label className="text-[10px] font-black text-slate-500 uppercase tracking-[0.2em]">
                                    {t('execution.team_planning.start_time')}
                                </label>
                                <input
                                    type="time"
                                    value={editForm.data.start_time}
                                    onChange={(e) =>
                                        editForm.setData(
                                            "start_time",
                                            e.target.value,
                                        )
                                    }
                                    className="w-full bg-slate-50 dark:bg-slate-800 border-slate-200 dark:border-slate-700 rounded-xl text-sm font-bold focus:ring-blue-500 text-slate-900 dark:text-white"
                                />
                            </div>
                            <div className="space-y-2">
                                <label className="text-[10px] font-black text-slate-500 uppercase tracking-[0.2em]">
                                    {t('execution.team_planning.end_time')}
                                </label>
                                <input
                                    type="time"
                                    value={editForm.data.end_time}
                                    onChange={(e) =>
                                        editForm.setData(
                                            "end_time",
                                            e.target.value,
                                        )
                                    }
                                    className="w-full bg-slate-50 dark:bg-slate-800 border-slate-200 dark:border-slate-700 rounded-xl text-sm font-bold focus:ring-blue-500 text-slate-900 dark:text-white"
                                />
                            </div>
                        </div>

                        <div className="space-y-2 pt-2">
                            <label className="text-[10px] font-black text-slate-500 uppercase tracking-[0.2em]">
                                {t('tasks.status') || "Status"}
                            </label>
                            <select
                                value={editForm.data.status_task_assignment_id}
                                onChange={(e) => editForm.setData("status_task_assignment_id", e.target.value)}
                                className="w-full bg-slate-50 dark:bg-slate-800 border-slate-200 dark:border-slate-700 rounded-xl text-sm font-bold focus:ring-blue-500 text-slate-900 dark:text-white"
                            >
                                <option value="">{t('status_task_assignments.select_status_default') || "Select Status (Default: Assigned)"}</option>
                                {statusTaskAssignments.map((status) => (
                                    <option key={status.id} value={status.id}>
                                        {translateStatus(status.name)}
                                    </option>
                                ))}
                            </select>
                            {editForm.errors.status_task_assignment_id && (
                                <p className="text-red-500 text-xs font-bold mt-1">
                                    {editForm.errors.status_task_assignment_id}
                                </p>
                            )}
                        </div>

                        <DialogFooter className="pt-4">
                            <SecondaryButton
                                type="button"
                                onClick={() => setIsEditModalOpen(false)}
                            >
                                {t('execution.team_planning.cancel')}
                            </SecondaryButton>
                            <Button
                                type="submit"
                                disabled={editForm.processing}
                                className="rounded-2xl bg-blue-600 hover:bg-blue-700 text-white font-black px-8 shadow-lg shadow-blue-600/20"
                            >
                                {editForm.processing
                                    ? t('execution.team_planning.saving')
                                    : t('execution.team_planning.save_changes')}
                            </Button>
                        </DialogFooter>
                    </form>
                </DialogContent>
            </Dialog>

            {/* Contact Selector Modal for Edit */}
            <ContactSelectorModal
                show={isContactSelectorOpen}
                onClose={() => setIsContactSelectorOpen(false)}
                contacts={businessContacts}
                allowTiers={true}
                selectedContactId={editForm.data.business_contact_id || editForm.data.business_tier_id}
                onSelect={(contact) => {
                    const isTier = contact.is_tier !== undefined ? contact.is_tier : (contact.type !== "contact");
                    editForm.setData({
                        ...editForm.data,
                        business_tier_id: isTier ? contact.id : "",
                        business_contact_id: !isTier ? contact.id : "",
                        affaire_id: "", // clear affaire since contact is set
                    });
                    setIsContactSelectorOpen(false);
                }}
            />

            {/* Delete Confirmation Modal */}
            <Dialog open={isDeleteModalOpen} onOpenChange={setIsDeleteModalOpen}>
                <DialogContent className="max-w-md rounded-[2rem] bg-white dark:bg-slate-900 p-8 border-none shadow-2xl">
                    <DialogHeader className="flex flex-col items-center text-center space-y-4">
                        <div className="size-16 rounded-full bg-red-100 dark:bg-red-900/20 flex items-center justify-center text-red-600 dark:text-red-400">
                            <AlertTriangle className="size-8" />
                        </div>
                        <div className="space-y-1">
                            <DialogTitle className="text-2xl font-black tracking-tight text-slate-900 dark:text-white">
                                {t('execution.team_planning.remove_from_planning')}
                            </DialogTitle>
                            <p className="text-slate-500 font-medium">
                                {t('execution.team_planning.remove_warning')}
                            </p>
                        </div>
                    </DialogHeader>

                    <DialogFooter className="flex flex-row items-center justify-center gap-4 pt-6 border-none">
                        <CancelButton 
                            onClick={() => setIsDeleteModalOpen(false)} 
                            className="h-12 px-8"
                        />
                        <ConfirmDeleteButton 
                            onClick={confirmDelete} 
                            className="h-12 px-8"
                        >
                            {t('execution.team_planning.remove_task')}
                        </ConfirmDeleteButton>
                    </DialogFooter>
                </DialogContent>
            </Dialog>

            <StatusSwitcherModal
                show={isStatusSwitcherOpen}
                onClose={() => {
                    setIsStatusSwitcherOpen(false);
                    setSelectedStatusPlanning(null);
                }}
                planning={selectedStatusPlanning}
            />
        </AuthenticatedLayout>
    );
}
