"use client";
import React, { useState } from "react";
import { Eye, ChevronDown, ChevronLeft, ChevronRight, X, Plus, Calendar as CalIcon, Filter, Search, Pencil, Trash2, Archive, Undo2, Download } from "lucide-react";
import { DailyReport, DailySummary } from "@/types";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { fetchReports, fetchDailySummaries, createReport, updateReport, deleteReport, toggleArchiveReport } from "@/store/slices/reportSlice";
import { fetchProjects } from "@/store/slices/projectSlice";
import { fetchTasks } from "@/store/slices/taskSlice";
import { fetchTeam } from "@/store/slices/teamSlice";
import { useEffect } from "react";
import DataTable from "react-data-table-component";
import { useModal } from "@/hooks/useModal";
import { Modal } from "@/components/common/modal";
import { CalendarDaysIcon } from "@heroicons/react/24/outline";
import { useForm } from "react-hook-form";
import { toast } from "react-toastify";
import jsPDF from "jspdf";
import autoTable from "jspdf-autotable";
import axiosInstance from "@/lib/axios";

const formatTime = (val: any) => {
  if (typeof val === 'string' && val.includes('h') && val.includes('m')) return val;
  const decimalHours = Number(val);
  if (!decimalHours) return "00h 00m 00s";
  const totalSeconds = Math.round(decimalHours * 3600);
  const h = Math.floor(totalSeconds / 3600);
  const m = Math.floor((totalSeconds % 3600) / 60);
  const s = totalSeconds % 60;
  
  const pad = (num: number) => num.toString().padStart(2, '0');
  
  return `${pad(h)}h ${pad(m)}m ${pad(s)}s`;
};

export default function DailyReportsPage() {
  const dispatch = useAppDispatch();
  const reports = useAppSelector((state) => state.reports.reports);
  const summaries = useAppSelector((state) => state.reports.summaries);
  const projects = useAppSelector((state) => state.projects.projects);
  const tasks = useAppSelector((state) => state.tasks.tasks);
  const team = useAppSelector((state) => state.team.members);
  const authUser = useAppSelector((state: any) => state.auth.user);

  const hasPermission = (key: string) => {
    return authUser?.permissions?.some((p: any) => p.key === key) || false;
  };

  const isAdmin = authUser?.role?.toLowerCase() === 'admin';
  const canView = isAdmin || hasPermission('report.view') || hasPermission('dailyReport.view');
  const canEdit = isAdmin || hasPermission('report.update') || hasPermission('dailyReport.update');
  const canDelete = isAdmin || hasPermission('report.delete') || hasPermission('dailyReport.delete');
  const canCreate = isAdmin || hasPermission('report.create') || hasPermission('dailyReport.create');


  const [isArchiveView, setIsArchiveView] = useState(false);

  useEffect(() => {
    dispatch(fetchProjects({}));
    dispatch(fetchTasks({}));
    dispatch(fetchTeam({}));
  }, [dispatch]);

  const { isOpen, openModal, closeModal } = useModal();
  const { register, handleSubmit, reset, watch, setValue, setError, formState: { errors } } = useForm<Partial<DailyReport>>({
    defaultValues: { hoursWorked: 0, progressPercentage: 0, blockers: "None" }
  });
  const reportId = watch("id");
  const watchProjectId = watch("projectId");
  const watchTaskId = watch("taskId");

  useEffect(() => {
    if (watchProjectId && watchTaskId) {
      const task = tasks.find(t => t.id === watchTaskId);
      if (task && task.projectId !== watchProjectId && (task as any).project?.id !== watchProjectId) {
        setValue("taskId", "");
      }
    }
  }, [watchProjectId, watchTaskId, tasks, setValue]);

  const [selectedReport, setSelectedReport] = useState<DailyReport | null>(null);
  const [isViewModalOpen, setIsViewModalOpen] = useState(false);
  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
  const [reportToDelete, setReportToDelete] = useState<DailyReport | null>(null);

  const [isArchiveModalOpen, setIsArchiveModalOpen] = useState(false);
  const [isUndoArchiveModalOpen, setIsUndoArchiveModalOpen] = useState(false);
  const [reportToArchive, setReportToArchive] = useState<DailyReport | null>(null);
  const [reportToUndoArchive, setReportToUndoArchive] = useState<DailyReport | null>(null);

  const [searchText, setSearchText] = useState("");
  const [rowsPerPage, setRowsPerPage] = useState(10);
  const [currentPage, setCurrentPage] = useState(1);
  const [currentSummaryPage, setCurrentSummaryPage] = useState(1);
  const [resetPaginationToggle, setResetPaginationToggle] = useState(false);
  const [activeTab, setActiveTab] = useState<'updates' | 'summaries'>('updates');

  const [isSummaryViewModalOpen, setIsSummaryViewModalOpen] = useState(false);
  const [selectedSummary, setSelectedSummary] = useState<DailySummary | null>(null);

  const [excelStartDate, setExcelStartDate] = useState("");
  const [excelEndDate, setExcelEndDate] = useState("");

  useEffect(() => {
    const timer = setTimeout(() => {
      const params: any = { archived: isArchiveView, search: searchText };
      if (excelStartDate) params.startDate = excelStartDate;
      if (excelEndDate) params.endDate = excelEndDate;

      dispatch(fetchReports(params));
      dispatch(fetchDailySummaries(params));
    }, 500);
    return () => clearTimeout(timer);
  }, [dispatch, isArchiveView, searchText, excelStartDate, excelEndDate]);

  const handleOpenModal = () => {
    reset({
      id: undefined,
      userId: "",
      projectId: "",
      taskId: "",
      hoursWorked: 0,
      progressPercentage: 0,
      workDoneToday: "",
      tomorrowPlan: "",
      blockers: "None",
      date: new Date().toISOString().split('T')[0]
    });
    openModal();
  };

  const handleCloseModal = () => {
    reset({});
    closeModal();
  };

  const handleSaveReport = (data: Partial<DailyReport>) => {
    const selectedTask = tasks.find(t => t.id === data.taskId);
    if (selectedTask && selectedTask.projectId && selectedTask.projectId !== data.projectId && (selectedTask as any).project?.id !== data.projectId) {
      setError("taskId", { type: "manual", message: "Task does not belong to the selected project" });
      return;
    }

    if (data.id) {
      dispatch(updateReport({ id: data.id, data })).then((resultAction: any) => {
        if (updateReport.fulfilled.match(resultAction)) {
          toast.success("Report updated successfully");
          dispatch(fetchReports({}));
          handleCloseModal();
        } else {
          toast.error(resultAction.payload?.message || resultAction.payload || "Failed to update report");
        }
      });
    } else {
      dispatch(createReport(data)).then((resultAction: any) => {
        if (createReport.fulfilled.match(resultAction)) {
          toast.success("Report created successfully");
          dispatch(fetchReports({}));
          handleCloseModal();
        } else {
          toast.error(resultAction.payload?.message || resultAction.payload || "Failed to create report");
        }
      });
    }
  };

  const handleViewReport = (report: DailyReport) => {
    setSelectedReport(report);
    setIsViewModalOpen(true);
  };

  const handleEditReport = (report: any) => {
    reset({
      ...report,
      projectId: report.project?.id || report.projectId,
      taskId: report.task?.id || report.taskId,
      userId: report.user?.id || report.userId,
      date: report.date ? new Date(report.date).toISOString().split('T')[0] : ''
    });
    openModal();
  };

  const handleDeleteReport = (report: DailyReport) => {
    setReportToDelete(report);
    setIsDeleteModalOpen(true);
  };

  const confirmDelete = () => {
    if (reportToDelete) {
      dispatch(deleteReport(reportToDelete.id)).then((resultAction: any) => {
        if (deleteReport.fulfilled.match(resultAction)) {
          toast.success("Report deleted successfully");
          dispatch(fetchReports({}));
          dispatch(fetchDailySummaries({ search: searchText }));
        } else {
          toast.error(resultAction.payload?.message || resultAction.payload || "Failed to delete report");
        }
        setIsDeleteModalOpen(false);
        setReportToDelete(null);
      });
    }
  };

  const closeDeleteModal = () => {
    setIsDeleteModalOpen(false);
    setReportToDelete(null);
  };

  const handleArchiveReport = (report: DailyReport) => {
    setReportToArchive(report);
    setIsArchiveModalOpen(true);
  };

  const handleUndoArchiveReport = (report: DailyReport) => {
    setReportToUndoArchive(report);
    setIsUndoArchiveModalOpen(true);
  };

  const confirmArchive = () => {
    if (reportToArchive) {
      dispatch(toggleArchiveReport(reportToArchive.id)).then((resultAction: any) => {
        if (toggleArchiveReport.fulfilled.match(resultAction)) {
          toast.success("Report archived successfully");
          dispatch(fetchReports({ archived: isArchiveView }));
        } else {
          toast.error(resultAction.payload?.message || resultAction.payload || "Failed to archive report");
        }
        setIsArchiveModalOpen(false);
        setReportToArchive(null);
      });
    }
  };

  const confirmUndoArchive = () => {
    if (reportToUndoArchive) {
      dispatch(toggleArchiveReport(reportToUndoArchive.id)).then((resultAction: any) => {
        if (toggleArchiveReport.fulfilled.match(resultAction)) {
          toast.success("Report un-archived successfully");
          dispatch(fetchReports({ archived: isArchiveView }));
        } else {
          toast.error(resultAction.payload?.message || resultAction.payload || "Failed to un-archive report");
        }
        setIsUndoArchiveModalOpen(false);
        setReportToUndoArchive(null);
      });
    }
  };

  const closeArchiveModal = () => {
    setIsArchiveModalOpen(false);
    setReportToArchive(null);
  };

  const closeUndoArchiveModal = () => {
    setIsUndoArchiveModalOpen(false);
    setReportToUndoArchive(null);
  };
  const closeViewModal = () => {
    setIsViewModalOpen(false);
    setSelectedReport(null);
  };

  const columns = [
    {
      name: 'S.No.',
      selector: (_row: DailyReport, index?: number) => (index !== undefined ? (currentPage - 1) * rowsPerPage + index + 1 : 0),
      sortable: false,
      width: "80px",
      cell: (_row: DailyReport, index?: number) => (
        <div data-th="S.No." className="mobile-cell text-sm text-gray-600">
          {index !== undefined ? (currentPage - 1) * rowsPerPage + index + 1 : ''}
        </div>
      )
    },
    {
      name: 'Date',
      selector: (row: DailyReport) => row.date,
      sortable: true,
      minWidth: "120px",
      cell: (row: DailyReport) => (
        <div data-th="Date" className="mobile-cell flex items-center gap-1.5 text-gray-600 text-sm">
          {row.date}
        </div>
      )
    },
    {
      name: 'Developer',
      selector: (row: DailyReport) => row.userId,
      sortable: true,
      minWidth: "160px",
      cell: (row: DailyReport) => {
        const user = team.find(u => u.id === row.userId);
        return (
          <div data-th="Developer" className="mobile-cell flex items-center gap-2">
            <div className="w-8 h-8 rounded-full bg-brand-950/10 flex items-center justify-center text-brand-950 text-xs font-bold shrink-0">
              {user?.name.charAt(0) || '?'}
            </div>
            <span className="md:font-medium text-gray-600 md:text-gray-900 text-sm">{user?.name || row.userId}</span>
          </div>
        );
      }
    },
    {
      name: 'Project',
      selector: (row: DailyReport) => row.projectId,
      sortable: true,
      minWidth: "160px",
      cell: (row: DailyReport) => {
        const project = projects.find(p => p.id === row.projectId);
        return <div data-th="Project" className="mobile-cell"><span className="text-gray-600 text-sm">{project?.name || row.projectId}</span></div>;
      }
    },
    {
      name: 'Task',
      selector: (row: DailyReport) => row.taskId,
      sortable: true,
      minWidth: "140px",
      cell: (row: DailyReport) => {
        const task = tasks.find(t => t.id === row.taskId);
        return (
          <div data-th="Task" className="mobile-cell">
            <span className="text-gray-600 text-sm" title={task?.title}>
              {task?.title || row.taskId}
            </span>
          </div>
        );
      }
    },
    {
      name: 'Hours',
      selector: (row: DailyReport) => row.hoursWorked,
      sortable: true,
      minWidth: "150px",
      cell: (row: DailyReport) => (
        <div data-th="Hours" className="mobile-cell">
          <span className="px-2.5 py-1 bg-gray-100 text-gray-700 rounded text-sm font-medium whitespace-nowrap">
            {formatTime(row.hoursWorked || 0)}
          </span>
        </div>
      )
    },
    {
      name: 'Progress',
      selector: (row: DailyReport) => row.progressPercentage,
      sortable: true,
      minWidth: "160px",
      cell: (row: DailyReport) => (
        <div data-th="Progress" className="mobile-cell flex items-center gap-2 w-full">
          <div className="w-full bg-gray-200 rounded-full h-2 min-w-[60px] max-w-[100px]">
            <div
              className="bg-green-500 h-2 rounded-full"
              style={{ width: `${row.progressPercentage}%` }}
            ></div>
          </div>
          <span className="text-xs font-medium text-gray-600">{row.progressPercentage}%</span>
        </div>
      )
    }
  ];

  if (canView || canEdit || canDelete) {
    columns.push({
      name: 'Action',
      center: true,
      minWidth: "160px",
      cell: (row: DailyReport) => (
        <div data-th="Action" className="mobile-cell w-full sm:w-auto">
          <div className="flex justify-start sm:justify-center gap-2">
            {!isArchiveView ? (
              <>
                {canView && (
                  <button
                    className="cursor-pointer w-8 h-8 rounded-md bg-brand-950/10 flex items-center justify-center text-brand-950 hover:bg-brand-950/20 transition-colors"
                    onClick={() => handleViewReport(row)}
                    title="View Report"
                  >
                    <Eye size={18} />
                  </button>
                )}
                {canEdit && (
                  <button
                    className="w-8 h-8 rounded-md bg-amber-500/10 flex items-center justify-center text-amber-600 hover:bg-amber-500/20 transition-colors"
                    onClick={() => handleEditReport(row)}
                    title="Edit Report"
                  >
                    <Pencil size={18} />
                  </button>
                )}
                {canDelete && (
                  <button
                    className="w-8 h-8 rounded-md bg-red-500/10 flex items-center justify-center text-red-500 hover:bg-red-500/20 transition-colors"
                    onClick={() => handleDeleteReport(row)}
                    title="Delete Report"
                  >
                    <Trash2 size={18} />
                  </button>
                )}
                {canEdit && (
                  <button
                    className="w-8 h-8 rounded-md bg-gray-500/10 flex items-center justify-center text-gray-600 hover:bg-gray-500/20 transition-colors"
                    onClick={() => handleArchiveReport(row)}
                    title="Archive Report"
                  >
                    <Archive size={18} />
                  </button>
                )}
              </>
            ) : (
              <>
                {canEdit && (
                  <button
                    className="w-8 h-8 rounded-md bg-gray-500/10 flex items-center justify-center text-gray-600 hover:bg-gray-500/20 transition-colors"
                    onClick={() => handleUndoArchiveReport(row)}
                    title="Un-Archive Report"
                  >
                    <Undo2 size={18} />
                  </button>
                )}
              </>
            )}
          </div>
        </div>
      )
    } as any);
  }

  const filteredReports = reports.filter((report) => {
    const user = team.find(u => u.id === report.userId);
    const project = projects.find(p => p.id === report.projectId);
    const searchLower = searchText.toLowerCase();

    return (
      (user?.name || '').toLowerCase().includes(searchLower) ||
      (project?.name || '').toLowerCase().includes(searchLower) ||
      (report.date || '').toLowerCase().includes(searchLower)
    );
  });

  const filteredSummaries = summaries.filter((summary) => {
    const userName = summary.developer?.firstName ? `${summary.developer.firstName} ${summary.developer.lastName}` : (team.find(u => u.id === summary.developerId)?.name || summary.developerId);
    const projectName = summary.project?.title || projects.find(p => p.id === summary.projectId)?.name || summary.projectId;
    const searchLower = searchText.toLowerCase();

    return (
      (userName || '').toLowerCase().includes(searchLower) ||
      (projectName || '').toLowerCase().includes(searchLower) ||
      String(summary.reportDate || '').toLowerCase().includes(searchLower)
    );
  });

  const handleExportPDF = () => {
    const doc = new jsPDF();
    doc.text("Daily Summaries", 14, 15);

    const tableData = filteredSummaries.map((summary, index) => {
      const user = summary.developer?.firstName ? `${summary.developer.firstName} ${summary.developer.lastName}` : (team.find(u => u.id === summary.developerId)?.name || summary.developerId);
      const project = summary.project?.title || projects.find(p => p.id === summary.projectId)?.name || summary.projectId;
      return [
        index + 1,
        summary.reportDate ? String(summary.reportDate).split('T')[0] : 'N/A',
        user,
        project,
        summary.totalTasksUpdated?.toString() || '0',
        `${summary.totalHoursSpent || 0} hrs`
      ];
    });

    autoTable(doc, {
      startY: 20,
      head: [['S.No.', 'Date', 'Developer', 'Project', 'Total Tasks', 'Total Hours']],
      body: tableData,
      theme: 'grid',
      styles: { fontSize: 9 },
      headStyles: { fillColor: [37, 57, 92] }
    });

    doc.save("Daily_Summaries.pdf");
  };

  const handleDownloadGoogleSheet = async () => {
    let startDate = excelStartDate;
    let endDate = excelEndDate;

    if (!startDate && !endDate) {
      const today = new Date().toISOString().split('T')[0];
      startDate = today;
      endDate = today;
    } else if (startDate && !endDate) {
      endDate = startDate;
    } else if (!startDate && endDate) {
      startDate = endDate;
    }

    try {
      const response = await axiosInstance.get('/api/daily-reports/download-excel', {
        params: {
          startDate,
          endDate,
          format: 'csv'
        },
        responseType: 'blob',
      });

      const blob = new Blob([response.data], { type: 'text/csv;charset=utf-8;' });
      const link = document.createElement("a");
      const url = URL.createObjectURL(blob);
      link.setAttribute("href", url);
      link.setAttribute("download", `Daily_Reports_${startDate}_to_${endDate}.csv`);
      link.style.visibility = 'hidden';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.open('https://docs.google.com/spreadsheets/', '_blank');
      toast.success("CSV downloaded successfully. You can import this into Google Sheets!");
    } catch (error) {
      toast.error("Failed to download CSV report.");
      console.error(error);
    }
  };

  const handleDownloadExcel = async () => {
    let startDate = excelStartDate;
    let endDate = excelEndDate;

    if (!startDate && !endDate) {
      const today = new Date().toISOString().split('T')[0];
      startDate = today;
      endDate = today;
    } else if (startDate && !endDate) {
      endDate = startDate;
    } else if (!startDate && endDate) {
      startDate = endDate;
    }

    try {
      const response = await axiosInstance.get('/api/daily-reports/download-excel', {
        params: {
          startDate,
          endDate,
        },
        responseType: 'blob',
      });

      const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      const link = document.createElement("a");
      const url = URL.createObjectURL(blob);
      link.setAttribute("href", url);
      link.setAttribute("download", `Daily_Reports_${startDate}_to_${endDate}.xlsx`);
      link.style.visibility = 'hidden';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      toast.success("Excel downloaded successfully.");
    } catch (error) {
      toast.error("Failed to download Excel report.");
      console.error(error);
    }
  };

  return (
    <div className="min-h-screen">
      <div className="mx-auto max-w-[1500px] space-y-6">
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6">
          <div className="flex flex-col gap-2">
            <h1 className="text-xl lg:text-2xl font-medium text-brand-950">Daily Summaries</h1>
          </div>
          <div className="flex items-center gap-3">
            <div className="flex items-center gap-2">
              <div className="relative">
                <input
                  type="date"
                  value={excelStartDate}
                  onChange={(e) => setExcelStartDate(e.target.value)}
                  className="h-11 w-[140px] rounded-lg border appearance-none px-3 pr-10 py-2 text-sm shadow-theme-xs placeholder:text-gray-400 bg-white text-gray-800 border-gray-300 outline-none"
                  title="Start Date"
                />
                <CalendarDaysIcon
                  className="absolute right-3 top-1/2 -translate-y-1/2 h-5 w-5 text-gray-400 cursor-pointer"
                  onClick={(e) => {
                    const input = e.currentTarget.parentElement?.querySelector("input") as HTMLInputElement;
                    input?.showPicker?.();
                    input?.focus();
                  }}
                />
              </div>
              <span className="text-gray-500 text-sm font-medium">to</span>
              <div className="relative">
                <input
                  type="date"
                  value={excelEndDate}
                  onChange={(e) => setExcelEndDate(e.target.value)}
                  className="h-11 w-[140px] rounded-lg border appearance-none px-3 pr-10 py-2 text-sm shadow-theme-xs placeholder:text-gray-400 bg-white text-gray-800 border-gray-300 outline-none"
                  title="End Date"
                />
                <CalendarDaysIcon
                  className="absolute right-3 top-1/2 -translate-y-1/2 h-5 w-5 text-gray-400 cursor-pointer"
                  onClick={(e) => {
                    const input = e.currentTarget.parentElement?.querySelector("input") as HTMLInputElement;
                    input?.showPicker?.();
                    input?.focus();
                  }}
                />
              </div>
            </div>
            <div className="flex items-center gap-2">
              <button
                onClick={handleDownloadGoogleSheet}
                className="inline-flex items-center justify-center font-medium gap-2 rounded-lg transition px-2.5 lg:px-4 py-2.5 lg:py-3 text-sm border border-blue-300 bg-white text-blue-700 shadow-theme-xs hover:bg-blue-50"
              >
                <Download size={18} className="text-blue-600" />
                <span className="hidden lg:inline-block">Google Sheet</span>
              </button>
              <button
                onClick={handleDownloadExcel}
                className="inline-flex items-center justify-center font-medium gap-2 rounded-lg transition px-2.5 lg:px-4 py-2.5 lg:py-3 text-sm border border-green-300 bg-white text-green-700 shadow-theme-xs hover:bg-green-50"
              >
                <Download size={18} className="text-green-600" />
                <span className="hidden lg:inline-block">Download Excel</span>
              </button>
            </div>
          </div>
        </div>

        {/* Reports Table */}
        <div className="rounded-xl bg-white p-6 shadow-theme-md">
          <div className="md:border border-gray-200 rounded-lg overflow-hidden">
            <div className="flex items-center justify-between md:border-b md:px-4 pb-4 md:py-4">
              <div className="hidden md:flex items-center gap-2">
                <span className="text-sm font-normal text-gray-500 block">Show</span>
                <div className="relative">
                  <select
                    value={rowsPerPage}
                    onChange={(e) => {
                      setRowsPerPage(Number(e.target.value));
                      setCurrentPage(1);
                      setCurrentSummaryPage(1);
                      setResetPaginationToggle(!resetPaginationToggle);
                    }}
                    className="w-full rounded-lg border appearance-none px-3 py-2 pr-8 text-sm shadow-theme-xs placeholder:text-gray-400 bg-transparent text-gray-800 border-gray-300 outline-none"
                  >
                    <option value={10}>10</option>
                    <option value={20}>20</option>
                    <option value={30}>30</option>
                    <option value={50}>50</option>
                  </select>
                  <span className="absolute text-gray-500 -translate-y-1/2 pointer-events-none right-2 top-1/2">
                    <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="none">
                      <path stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.5" d="M4.792 7.396 10 12.604l5.208-5.208"></path>
                    </svg>
                  </span>
                </div>
                <span className="text-sm font-normal text-gray-500">entries</span>
              </div>
              <div className="flex items-center gap-4 w-full sm:w-auto">
                <div className="relative block w-full sm:w-auto">
                  <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" size={16} />
                  <input
                    type="text"
                    placeholder="Search reports..."
                    value={searchText}
                    onChange={(e) => setSearchText(e.target.value)}
                    className="h-11 w-full rounded-lg border appearance-none py-2.5 pl-9 pr-4 text-sm shadow-theme-xs placeholder:text-gray-400 bg-transparent text-gray-800 border-gray-300 outline-none"
                  />
                </div>
              </div>
            </div>

            <div className="overflow-x-auto">
              <DataTable
                columns={[
                  {
                    name: 'S.No.',
                    selector: (row: any, index?: number) => (index !== undefined ? (currentSummaryPage - 1) * rowsPerPage + index + 1 : 0),
                    sortable: false,
                    width: "80px",
                    cell: (row: any, index?: number) => (
                      <div data-th="S.No." className="mobile-cell text-sm text-gray-600">
                        {index !== undefined ? (currentSummaryPage - 1) * rowsPerPage + index + 1 : ''}
                      </div>
                    )
                  },
                  {
                    name: 'Date',
                    selector: (row: any) => row.reportDate,
                    sortable: true,
                    cell: (row: any) => <span className="text-sm text-gray-600">{row.reportDate ? String(row.reportDate).split('T')[0] : 'N/A'}</span>
                  },
                  {
                    name: 'Developer',
                    selector: (row: any) => row.developer?.firstName || '',
                    sortable: true,
                    cell: (row: any) => {
                      const name = row.developer?.firstName ? `${row.developer.firstName} ${row.developer.lastName}` : (team.find(u => u.id === row.developer?.id)?.name || '-');
                      return <span className="text-sm font-medium text-gray-900">{name}</span>;
                    }
                  },
                  {
                    name: 'Project',
                    selector: (row: any) => row.project?.title || '',
                    sortable: true,
                    minWidth: "150px",
                    cell: (row: any) => {
                      const project = row.project?.title || projects.find(p => p.id === row.project?.id)?.name || '-';
                      return <span className="text-sm text-gray-600">{project}</span>;
                    }
                  },
                  {
                    name: 'Task Name',
                    selector: (row: any) => row.task?.title || '',
                    minWidth: "250px",
                    sortable: true,
                    cell: (row: any) => {
                      const taskName = row.task?.title || '-';
                      return (
                        <div className="flex flex-col gap-1 py-2">
                          <div className="text-sm font-medium text-brand-950 truncate">
                            {taskName}
                          </div>
                        </div>
                      );
                    }
                  },
                  {
                    name: 'Task Summary',
                    selector: (row: any) => row.workDoneToday || '',
                    minWidth: "300px",
                    cell: (row: any) => {
                      const summaryText = row.workDoneToday || '-';
                      return (
                        <div className="flex flex-col gap-1 py-2 w-full">
                          <div className="text-sm text-gray-600 line-clamp-2">
                            {summaryText}
                          </div>
                        </div>
                      );
                    }
                  },
                  {
                    name: 'Tomorrow Plan',
                    selector: (row: any) => row.planForTomorrow,
                    minWidth: "200px",
                    cell: (row: any) => <span className="text-sm text-gray-600 line-clamp-2">{row.planForTomorrow || '-'}</span>
                  },
                  {
                    name: 'Blockers',
                    selector: (row: any) => row.blockers,
                    minWidth: "150px",
                    cell: (row: any) => {
                      if (!row.blockers || row.blockers === "None") return <span className="text-sm text-gray-400">-</span>;
                      return <span className="text-sm text-red-600 line-clamp-2">{row.blockers}</span>;
                    }
                  },
                  {
                    name: 'Total Tasks',
                    selector: (row: any) => row.id,
                    sortable: false,
                    width: "110px",
                    cell: (row: any) => <span className="text-sm text-gray-600 font-medium text-center w-full">1</span>
                  },
                  {
                    name: 'Total Hours',
                    selector: (row: any) => row.timeSpent || row.totalHoursSpent,
                    sortable: true,
                    width: "150px",
                    cell: (row: any) => <span className="px-2.5 py-1 bg-blue-50 text-blue-700 rounded text-sm font-medium w-max whitespace-nowrap">{formatTime(row.timeSpent || row.totalHoursSpent || 0)}</span>
                  },
                  {
                    name: 'Action',
                    center: true,
                    minWidth: "140px",
                    cell: (row: any) => (
                      <div data-th="Action" className="mobile-cell w-full sm:w-auto">
                        <div className="flex justify-start sm:justify-center gap-2">
                          <button
                            className="cursor-pointer w-8 h-8 rounded-md bg-brand-950/10 flex items-center justify-center text-brand-950 hover:bg-brand-950/20 transition-colors"
                            onClick={() => {
                              handleViewReport(row as any);
                            }}
                            title="View Summary"
                          >
                            <Eye size={18} />
                          </button>
                          <button
                            className="cursor-pointer w-8 h-8 rounded-md bg-red-50 flex items-center justify-center text-red-600 hover:bg-red-100 transition-colors border border-red-100"
                            onClick={() => {
                              handleDeleteReport(row as any);
                            }}
                            title="Delete Summary"
                          >
                            <Trash2 size={16} />
                          </button>
                        </div>
                      </div>
                    )
                  }
                ]}
                data={filteredSummaries.slice((currentSummaryPage - 1) * rowsPerPage, currentSummaryPage * rowsPerPage)}
                pagination
                key={`summaries-table-${rowsPerPage}`}
                paginationServer
                paginationTotalRows={filteredSummaries.length}
                paginationResetDefaultPage={resetPaginationToggle}
                paginationPerPage={rowsPerPage}
                onChangePage={(page) => setCurrentSummaryPage(page)}
                onChangeRowsPerPage={(newPerPage, page) => {
                  setRowsPerPage(newPerPage);
                  setCurrentPage(page);
                  setCurrentSummaryPage(page);
                }}
                paginationComponentOptions={{ noRowsPerPage: true }}
                highlightOnHover
                customStyles={{
                  headRow: {
                    style: {
                      backgroundColor: '#ffffff',
                      color: '#1E293B',
                      fontWeight: 600,
                      fontSize: '14px',
                      borderBottom: '1px solid #F1F5F9',
                    },
                  },
                  rows: {
                    style: {
                      fontSize: '14px',
                      color: '#475569',
                      minHeight: '60px',
                      borderBottom: '1px solid #F1F5F9',
                    },
                  },
                }}
              />
            </div>
          </div>
        </div>

        {/* Submit Report Modal */}
        <Modal isOpen={isOpen} onClose={handleCloseModal} className="max-w-[700px] m-4">
          <div className="no-scrollbar relative w-full max-w-[700px] rounded-3xl bg-white p-4 lg:p-8">
            <div className="px-2 pr-14 mb-6 lg:mb-7">
              <h4 className="text-xl lg:text-2xl font-semibold text-brand-950">
                {reportId ? "Edit Daily Work Report" : "Submit Daily Work Report"}
              </h4>
            </div>

            <form onSubmit={handleSubmit(handleSaveReport)} className="px-2 space-y-6 lg:space-y-5">
              <div className="grid grid-cols-1 gap-x-6 gap-y-5 lg:grid-cols-2">
                <div className="col-span-2 lg:col-span-1">
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Developer</label>
                  <div className="relative">
                    <select
                      {...register("userId", { required: "Developer is required" })}
                      className={`h-11 w-full rounded-lg border appearance-none px-4 py-2.5 text-sm shadow-theme-xs placeholder:text-gray-400 bg-transparent text-gray-800 outline-none ${errors.userId ? 'border-red-500' : 'border-gray-300'}`}
                    >
                      <option value="" disabled>Select your name...</option>
                      {team.map(u => <option key={u.id} value={u.id}>{u.name}</option>)}
                    </select>
                    <span className="absolute text-gray-500 -translate-y-1/2 pointer-events-none right-3 top-1/2">
                      <ChevronDown size={20} />
                    </span>
                  </div>
                  {errors.userId && <p className="text-red-500 text-xs mt-1">{errors.userId.message as string}</p>}
                </div>

                <div className="col-span-2 lg:col-span-1">
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Date</label>
                  <div className="relative">
                    <input
                      type="date"
                      {...register("date", { required: "Date is required" })}
                      className={`h-11 w-full rounded-lg border appearance-none px-4 py-2.5 text-sm shadow-theme-xs placeholder:text-gray-400 bg-transparent text-gray-800 outline-none ${errors.date ? 'border-red-500' : 'border-gray-300'}`}
                    />
                    <CalendarDaysIcon
                      className="absolute right-3 top-1/2 -translate-y-1/2 h-5 w-5 text-gray-400 cursor-pointer"
                      onClick={(e) => {
                        const input = e.currentTarget.parentElement?.querySelector(
                          "input"
                        ) as HTMLInputElement;
                        input?.showPicker?.();
                        input?.focus();
                      }}
                    />
                  </div>
                  {errors.date && <p className="text-red-500 text-xs mt-1">{errors.date.message as string}</p>}
                </div>

                <div className="col-span-2 lg:col-span-1">
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Project</label>
                  <div className="relative">
                    <select
                      {...register("projectId", { required: "Project is required" })}
                      className={`h-11 w-full rounded-lg border appearance-none px-4 py-2.5 text-sm shadow-theme-xs placeholder:text-gray-400 bg-transparent text-gray-800 outline-none ${errors.projectId ? 'border-red-500' : 'border-gray-300'}`}
                    >
                      <option value="" disabled>Select Project...</option>
                      {projects.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
                    </select>
                    <span className="absolute text-gray-500 -translate-y-1/2 pointer-events-none right-3 top-1/2">
                      <ChevronDown size={20} />
                    </span>
                  </div>
                  {errors.projectId && <p className="text-red-500 text-xs mt-1">{errors.projectId.message as string}</p>}
                </div>

                <div className="col-span-2 lg:col-span-1">
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Task</label>
                  <div className="relative">
                    <select
                      {...register("taskId", { required: "Task is required" })}
                      className={`h-11 w-full rounded-lg border appearance-none px-4 py-2.5 text-sm shadow-theme-xs placeholder:text-gray-400 bg-transparent text-gray-800 outline-none ${errors.taskId ? 'border-red-500' : 'border-gray-300'}`}
                    >
                      <option value="" disabled>Select Task...</option>
                      {tasks.filter(t => !watchProjectId || t.projectId === watchProjectId || (t as any).project?.id === watchProjectId).map(t => <option key={t.id} value={t.id}>{t.title}</option>)}
                    </select>
                    <span className="absolute text-gray-500 -translate-y-1/2 pointer-events-none right-3 top-1/2">
                      <ChevronDown size={20} />
                    </span>
                  </div>
                  {errors.taskId && <p className="text-red-500 text-xs mt-1">{errors.taskId.message as string}</p>}
                </div>

                <div className="col-span-2 lg:col-span-1">
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Hours Worked</label>
                  <input
                    type="number"
                    min="0.5"
                    step="0.5"
                    {...register("hoursWorked", { required: "Hours Worked is required", min: { value: 0.5, message: "Min 0.5 hours" }, max: { value: 24, message: "Max 24 hours" }, valueAsNumber: true })}
                    className={`h-11 w-full rounded-lg border appearance-none px-4 py-2.5 text-sm shadow-theme-xs placeholder:text-gray-400 bg-transparent text-gray-800 outline-none ${errors.hoursWorked ? 'border-red-500' : 'border-gray-300'}`}
                    placeholder="e.g. 8"
                  />
                  {errors.hoursWorked && <p className="text-red-500 text-xs mt-1">{errors.hoursWorked.message as string}</p>}
                </div>

                <div className="col-span-2 lg:col-span-1">
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Progress (%)</label>
                  <input
                    type="number"
                    min="0"
                    max="100"
                    {...register("progressPercentage", { required: "Progress is required", min: { value: 0, message: "Min 0" }, max: { value: 100, message: "Max 100" }, valueAsNumber: true })}
                    className={`h-11 w-full rounded-lg border appearance-none px-4 py-2.5 text-sm shadow-theme-xs placeholder:text-gray-400 bg-transparent text-gray-800 outline-none ${errors.progressPercentage ? 'border-red-500' : 'border-gray-300'}`}
                  />
                  {errors.progressPercentage && <p className="text-red-500 text-xs mt-1">{errors.progressPercentage.message as string}</p>}
                </div>

                <div className="col-span-2">
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Work Done Today</label>
                  <textarea
                    {...register("workDoneToday", { required: "Work Completed is required" })}
                    className={`w-full rounded-lg border appearance-none px-4 py-2.5 text-sm shadow-theme-xs placeholder:text-gray-400 bg-transparent text-gray-800 outline-none min-h-[80px] align-middle ${errors.workDoneToday ? 'border-red-500' : 'border-gray-300'}`}
                    placeholder="Describe the work you've completed today..."
                  />
                  {errors.workDoneToday && <p className="text-red-500 text-xs mt-1">{errors.workDoneToday.message as string}</p>}
                </div>

                <div className="col-span-2">
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Plan for Tomorrow</label>
                  <textarea
                    {...register("tomorrowPlan", { required: "Plan for tomorrow is required" })}
                    className={`w-full rounded-lg border appearance-none px-4 py-2.5 text-sm shadow-theme-xs placeholder:text-gray-400 bg-transparent text-gray-800 outline-none min-h-[60px] align-middle ${errors.tomorrowPlan ? 'border-red-500' : 'border-gray-300'}`}
                    placeholder="What will you work on tomorrow?"
                  />
                  {errors.tomorrowPlan && <p className="text-red-500 text-xs mt-1">{errors.tomorrowPlan.message as string}</p>}
                </div>

                <div className="col-span-2">
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Blockers (if any)</label>
                  <input
                    type="text"
                    {...register("blockers")}
                    className="h-11 w-full rounded-lg border appearance-none px-4 py-2.5 text-sm shadow-theme-xs placeholder:text-gray-400 bg-transparent text-red-600 border-gray-300 outline-none"
                    placeholder="e.g. Waiting on API response from third party..."
                  />
                </div>

              </div>

              <div className="flex items-center gap-3 mt-6 lg:justify-end">
                <button
                  type="button"
                  onClick={handleCloseModal}
                  className="flex items-center justify-center gap-2 rounded-lg border border-gray-300 bg-[#f7f8fa] px-4 py-3 text-sm font-medium text-gray-700"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  className="inline-flex items-center justify-center font-medium gap-2 rounded-lg transition px-4 py-3 text-sm bg-brand-950 text-white shadow-theme-xs hover:text-brand-950 hover:bg-yellow-500 disabled:bg-yellow-500 disabled:opacity-50"
                >
                  {reportId ? "Save Changes" : "Submit Report"}
                </button>
              </div>
            </form>
          </div>
        </Modal>

        {/* Review Report Modal (For Individual Task Updates) */}
        {selectedReport && (
          <Modal isOpen={isViewModalOpen} onClose={closeViewModal} showCloseButton={true} className="max-w-[700px] m-4">
            <div className="no-scrollbar relative w-full rounded-3xl bg-white p-4 lg:p-8">
              <div className="mb-6 border-b border-gray-100 pb-5">
                <div className="flex items-start justify-between">
                  <div>
                    <h4 className="text-xl font-semibold text-brand-950">Daily Work Report</h4>
                    <p className="text-sm text-gray-500 mt-1">Submitted on {selectedReport.date}</p>
                  </div>
                </div>
              </div>

              <div className="space-y-6">
                <div className="bg-gray-50 rounded-xl p-5 border border-gray-100">
                  <h5 className="text-sm font-semibold text-gray-700 uppercase tracking-wider mb-4">Task Details</h5>
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-y-4 gap-x-8">
                    <div>
                      <p className="text-sm text-gray-500 font-normal">Project</p>
                      <p className="text-sm font-medium text-gray-800 mt-1">{projects.find(p => p.id === selectedReport.projectId)?.name || selectedReport.projectId}</p>
                    </div>
                    <div>
                      <p className="text-sm text-gray-500 font-normal">Task</p>
                      <p className="text-sm font-medium text-gray-800 mt-1">{tasks.find(t => t.id === selectedReport.taskId)?.title || selectedReport.taskId}</p>
                    </div>
                    <div>
                      <p className="text-sm text-gray-500 font-normal">Developer</p>
                      <p className="text-sm font-medium text-gray-800 mt-1">{team.find(u => u.id === selectedReport.userId)?.name || selectedReport.userId}</p>
                    </div>
                    <div>
                      <p className="text-sm text-gray-500 font-normal">Status</p>
                      <div className="mt-1">
                        {(() => {
                          const task = tasks.find(t => t.id === selectedReport.taskId);
                          const status = (selectedReport as any).previousStatus || (selectedReport as any).status || task?.status || 'N/A';

                          let bgClass = 'bg-gray-100 text-gray-800';
                          if (status === 'COMPLETED' || status === 'DONE') bgClass = 'bg-green-100 text-green-800';
                          else if (status === 'IN_PROGRESS') bgClass = 'bg-blue-100 text-blue-800';
                          else if (status === 'BLOCKED') bgClass = 'bg-red-100 text-red-800';
                          else if (status === 'TODO') bgClass = 'bg-amber-100 text-amber-800';
                          else if (status === 'IN_REVIEW') bgClass = 'bg-purple-100 text-purple-800';

                          return (
                            <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${bgClass}`}>
                              {status.replace(/_/g, ' ')}
                            </span>
                          );
                        })()}
                      </div>
                    </div>
                  </div>
                </div>

                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <div className="bg-white border border-gray-200 rounded-xl p-5 shadow-theme-xs">
                    <p className="text-sm text-gray-500 font-normal flex items-center gap-2">
                      <svg className="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
                      Time Logged
                    </p>
                    <p className="text-2xl font-semibold text-brand-950 mt-2">{selectedReport.hoursWorked} <span className="text-sm font-medium text-gray-500">hours</span></p>
                  </div>
                  <div className="bg-white border border-gray-200 rounded-xl p-5 shadow-theme-xs">
                    <p className="text-sm text-gray-500 font-normal flex items-center gap-2">
                      <svg className="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M13 7h8m0 0v8m0-8l-8 8-4-4-6 6"></path></svg>
                      Progress
                    </p>
                    <div className="flex items-center gap-3 mt-2">
                      <div className="flex-1 h-2.5 bg-gray-100 rounded-full overflow-hidden">
                        <div className="h-full bg-brand-950 rounded-full" style={{ width: `${selectedReport.progressPercentage}%` }}></div>
                      </div>
                      <p className="text-xl font-semibold text-brand-950">{selectedReport.progressPercentage}%</p>
                    </div>
                  </div>
                </div>

                <div className="bg-white border border-gray-200 rounded-xl p-1">
                  <div className="flex flex-col space-y-4 p-4">
                    <div>
                      <p className="text-sm font-medium text-gray-500">Work Done Today</p>
                      <p className="text-sm font-medium text-gray-800 mt-1.5">{selectedReport.workDoneToday}</p>
                    </div>
                    <div className="pt-4 border-t border-gray-100">
                      <p className="text-sm text-gray-500 font-normal">Plan for Tomorrow</p>
                      <p className="text-sm font-medium text-gray-800 mt-1.5">{selectedReport.tomorrowPlan}</p>
                    </div>
                  </div>
                </div>

                {selectedReport.blockers && selectedReport.blockers.toLowerCase() !== 'none' && (
                  <div>
                    <h5 className="mb-4 text-lg font-medium text-gray-800">Blockers</h5>
                    <div className="bg-red-50 border border-red-100 rounded-lg p-4">
                      <p className="text-sm font-medium text-red-700 whitespace-pre-wrap">{selectedReport.blockers}</p>
                    </div>
                  </div>
                )}
              </div>
            </div>
          </Modal>
        )}

        {/* View Summary Modal */}
        {selectedSummary && (
          <Modal isOpen={isSummaryViewModalOpen} onClose={() => setIsSummaryViewModalOpen(false)} showCloseButton={true} className="max-w-[800px] m-4">
            <div className="no-scrollbar relative w-full rounded-3xl bg-white p-4 lg:p-8">
              <div className="mb-6 border-b border-gray-100 pb-5">
                <div className="flex items-start justify-between">
                  <div>
                    <h4 className="text-xl font-semibold text-brand-950">Daily Summary Report</h4>
                    <p className="text-sm text-gray-500 mt-1">Submitted on {selectedSummary.reportDate ? String(selectedSummary.reportDate).split('T')[0] : 'N/A'}</p>
                  </div>
                </div>
              </div>

              <div className="space-y-6">
                <div className="bg-gray-50 rounded-xl p-5 border border-gray-100">
                  <h5 className="text-sm font-semibold text-gray-700 uppercase tracking-wider mb-4">Summary Overview</h5>
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-y-4 gap-x-8">
                    <div>
                      <p className="text-sm text-gray-500 font-normal">Project</p>
                      <p className="text-sm font-medium text-gray-800 mt-1">{selectedSummary.project?.title || projects.find(p => p.id === selectedSummary.projectId)?.name || selectedSummary.projectId}</p>
                    </div>
                    <div>
                      <p className="text-sm text-gray-500 font-normal">Developer</p>
                      <p className="text-sm font-medium text-gray-800 mt-1">{selectedSummary.developer?.firstName ? `${selectedSummary.developer.firstName} ${selectedSummary.developer.lastName}` : (team.find(u => u.id === selectedSummary.developerId)?.name || selectedSummary.developerId)}</p>
                    </div>
                    <div>
                      <p className="text-sm text-gray-500 font-normal">Total Tasks Updated</p>
                      <p className="text-sm font-medium text-gray-800 mt-1">{selectedSummary.totalTasksUpdated}</p>
                    </div>
                    <div>
                      <p className="text-sm text-gray-500 font-normal">Total Hours Spent</p>
                      <p className="text-sm font-medium text-gray-800 mt-1">{selectedSummary.totalHoursSpent} hours</p>
                    </div>
                  </div>
                </div>

                <div>
                  <h5 className="mb-3 text-sm font-semibold text-gray-700 uppercase tracking-wider">Tasks Completed Today</h5>
                  <div className="space-y-3">
                    {Array.isArray(selectedSummary.generatedSummary) && selectedSummary.generatedSummary.length > 0 ? (
                      selectedSummary.generatedSummary.map((task: any, idx: number) => (
                        <div key={idx} className="bg-white border border-gray-200 rounded-xl p-4 shadow-theme-xs">
                          <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2 mb-2">
                            <h6 className="font-semibold text-brand-950">{task.taskTitle}</h6>
                            <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-blue-50 text-blue-700 w-max">
                              {task.taskStatus}
                            </span>
                          </div>
                          <p className="text-sm text-gray-600"><span className="font-medium text-gray-800">Work Done:</span> {task.workDoneToday}</p>
                          {task.hasBlockers && task.blocker && task.blocker !== "None" && (
                            <p className="text-sm text-red-600 mt-1"><span className="font-medium">Blocker:</span> {task.blocker}</p>
                          )}
                          {task.comment && (
                            <p className="text-sm text-gray-500 mt-1 italic">"{task.comment}"</p>
                          )}
                        </div>
                      ))
                    ) : (
                      <p className="text-sm text-gray-500">No task details available.</p>
                    )}
                  </div>
                </div>

                <div className="bg-white border border-gray-200 rounded-xl p-5 shadow-theme-xs">
                  <div className="flex flex-col space-y-4">
                    <div>
                      <p className="text-sm text-gray-500 font-normal">Plan for Tomorrow</p>
                      <p className="text-sm font-medium text-gray-800 mt-1.5 whitespace-pre-wrap">{selectedSummary.tomorrowPlanSummary || '-'}</p>
                    </div>
                  </div>
                </div>

                {selectedSummary.blockersSummary && selectedSummary.blockersSummary !== "None" && (
                  <div>
                    <h5 className="mb-3 text-sm font-semibold text-gray-700 uppercase tracking-wider">Overall Blockers</h5>
                    <div className="bg-red-50 border border-red-100 rounded-xl p-4">
                      <p className="text-sm font-medium text-red-700 whitespace-pre-wrap">{selectedSummary.blockersSummary}</p>
                    </div>
                  </div>
                )}
              </div>
            </div>
          </Modal>
        )}

        {/* Delete Report Modal */}
        <Modal isOpen={isDeleteModalOpen} onClose={closeDeleteModal} showCloseButton={false} className="max-w-[450px] m-4">
          <div className="p-8">
            <div className="text-center">
              <h3 className="text-xl font-semibold text-brand-950 mb-4">Confirm Delete</h3>
              <p className="text-sm text-gray-500 mb-8 leading-relaxed">
                Are you sure you want to delete the report from <span className="font-semibold text-gray-800">{reportToDelete?.date}</span>?
              </p>
            </div>
            <div className="flex justify-center gap-3">
              <button onClick={closeDeleteModal} className="px-5 py-2.5 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-xl hover:bg-gray-50 transition-colors">
                Cancel
              </button>
              <button onClick={confirmDelete} className="px-5 py-2.5 text-sm font-medium text-white bg-brand-950 rounded-xl hover:text-brand-950 hover:bg-yellow-500 transition-colors">
                Delete
              </button>
            </div>
          </div>
        </Modal>

        {/* Archive Report Modal */}
        <Modal isOpen={isArchiveModalOpen} onClose={closeArchiveModal} showCloseButton={false} className="max-w-[450px] m-4">
          <div className="p-8">
            <div className="text-center">
              <h3 className="text-xl font-semibold text-brand-950 mb-4">Archive Report</h3>
              <p className="text-sm text-gray-500 mb-8 leading-relaxed">
                Are you sure you want to archive the report from <span className="font-semibold text-gray-800">{reportToArchive?.date}</span>?
              </p>
            </div>
            <div className="flex justify-center gap-3">
              <button onClick={closeArchiveModal} className="px-5 py-2.5 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-xl hover:bg-gray-50 transition-colors">
                Cancel
              </button>
              <button onClick={confirmArchive} className="px-5 py-2.5 text-sm font-medium text-white bg-brand-950 rounded-xl hover:text-brand-950 hover:bg-yellow-500 transition-colors">
                Archive
              </button>
            </div>
          </div>
        </Modal>

        {/* Undo Archive Report Modal */}
        <Modal isOpen={isUndoArchiveModalOpen} onClose={closeUndoArchiveModal} showCloseButton={false} className="max-w-[450px] m-4">
          <div className="p-8">
            <div className="text-center">
              <h3 className="text-xl font-semibold text-brand-950 mb-4">Un-Archive Report</h3>
              <p className="text-sm text-gray-500 mb-8 leading-relaxed">
                Are you sure you want to un-archive the report from <span className="font-semibold text-gray-800">{reportToUndoArchive?.date}</span>?
              </p>
            </div>
            <div className="flex justify-center gap-3">
              <button onClick={closeUndoArchiveModal} className="px-5 py-2.5 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-xl hover:bg-gray-50 transition-colors">
                Cancel
              </button>
              <button onClick={confirmUndoArchive} className="px-5 py-2.5 text-sm font-medium text-white bg-brand-950 rounded-xl hover:text-brand-950 hover:bg-yellow-500 transition-colors">
                Un-Archive
              </button>
            </div>
          </div>
        </Modal>
      </div>
    </div>
  );
}
