"use client";
import React, { useState, useEffect } from "react";
import { Eye, Trash2, ChevronDown, ChevronLeft, ChevronRight, X, Pencil, Plus, Paperclip, MessageSquare, Clock, AlignLeft, Search, CheckSquare, Square, Archive, Undo2 } from "lucide-react";
import { Task, Subtask } from "@/types";
import { useAppDispatch, useAppSelector } from "@/store/hooks";

import DataTable from "react-data-table-component";
import { CalendarDaysIcon } from "@heroicons/react/24/outline";
import { useModal } from "@/hooks/useModal";
import { Modal } from "@/components/common/modal";
import { MultiSelect } from "@/components/common/MultiSelect";
import { useForm } from "react-hook-form";
import { toast } from "react-toastify";
import axiosInstance from "@/lib/axios";

import { TaskTimer } from "@/components/TaskTimer/TaskTimer";
import { DailyReportModal, DailyReportFormData } from "@/components/DailyReport/DailyReportModal";

import { fetchTasks, createTask, updateTask, deleteTask, toggleArchiveTask } from "@/store/slices/taskSlice";
import { createReport } from "@/store/slices/reportSlice";
import { fetchTeam } from "@/store/slices/teamSlice";
import { fetchSprints } from "@/store/slices/sprintSlice";
import { fetchProjects } from "@/store/slices/projectSlice";
import { fetchMilestones } from "@/store/slices/milestoneSlice";

export default function TasksManagementPage() {
  const dispatch = useAppDispatch();
  const tasks = useAppSelector((state) => state.tasks.tasks);
  const sprints = useAppSelector((state) => state.sprints.sprints);
  const projects = useAppSelector((state) => state.projects.projects);
  const milestones = useAppSelector((state) => state.milestones.milestones);
  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?.roles?.some((r: any) => r.slug === 'admin') || authUser?.role?.toLowerCase() === 'admin';
  const canView = isAdmin || hasPermission('task.view');
  const canEdit = isAdmin || hasPermission('task.update');
  const canDelete = isAdmin || hasPermission('task.delete');
  const canCreate = isAdmin || hasPermission('task.create');

  const isDevOrMember = authUser?.roles?.some((r: any) =>
    !['admin', 'project-manager', 'team-leader'].includes(r.slug)
  ) || false;

  const { isOpen, openModal, closeModal } = useModal();
  const { register, handleSubmit, reset, watch, setValue, setError, clearErrors, formState: { errors } } = useForm<Partial<Task>>({
    defaultValues: { priority: "Medium", status: "TODO", estimatedHours: 0, actualHours: 0 }
  });
  const taskId = watch("id");
  const formSubtasks = watch("subtasks") || [];
  const formLabels = watch("labels") || [];
  const formAssignees = watch("assignees") || [];
  const watchProjectId = watch("projectId");
  const watchMilestoneId = watch("milestoneId");
  const taskStartDate = watch("startDate");

  const [newSubtask, setNewSubtask] = useState("");
  const [newLabel, setNewLabel] = useState("");

  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
  const [taskToDelete, setTaskToDelete] = useState<Task | null>(null);

  const [searchText, setSearchText] = useState("");
  const [rowsPerPage, setRowsPerPage] = useState(10);
  const [currentPage, setCurrentPage] = useState(1);
  const [resetPaginationToggle, setResetPaginationToggle] = useState(false);
  const total = useAppSelector((state) => state.tasks.total);
  const [selectedFileName, setSelectedFileName] = useState("");
  const [selectedFile, setSelectedFile] = useState<File | null>(null);

  const [isFilterModalOpen, setIsFilterModalOpen] = useState(false);

  const [hierarchyData, setHierarchyData] = useState<any[]>([]);

  useEffect(() => {
    if (isOpen) {
      axiosInstance.get(`/api/tasks/hierarchy`)
        .then(res => {
          if (res.data?.success && res.data?.data?.projects) {
            setHierarchyData(res.data.data.projects);
          } else {
            setHierarchyData([]);
          }
        })
        .catch(err => {
          console.error("Error fetching hierarchy", err);
          toast.error(err.response?.data?.message || err.message || "No active project found");
          setHierarchyData([]);
        });
    } else {
      setHierarchyData([]);
    }
  }, [isOpen]);

  const activeProjects = hierarchyData;
  const selectedProjectObj = activeProjects.find(p => p.id === watchProjectId);
  const activeMilestones = selectedProjectObj ? selectedProjectObj.milestones : [];
  const selectedMilestoneObj = activeMilestones.find((m: any) => m.id === watchMilestoneId);
  const activeSprints = selectedMilestoneObj ? selectedMilestoneObj.sprints : [];

  const [isViewModalOpen, setIsViewModalOpen] = useState(false);
  const [selectedTask, setSelectedTask] = useState<Task | null>(null);

  const [isArchiveView, setIsArchiveView] = useState(false);
  const [isArchiveModalOpen, setIsArchiveModalOpen] = useState(false);
  const [isUndoArchiveModalOpen, setIsUndoArchiveModalOpen] = useState(false);
  const [taskToArchive, setTaskToArchive] = useState<Task | null>(null);
  const [taskToUndoArchive, setTaskToUndoArchive] = useState<Task | null>(null);

  // Daily Report Timer & Modal state
  const [isReportModalOpen, setIsReportModalOpen] = useState(false);
  const [reportTask, setReportTask] = useState<Task | null>(null);
  const [reportElapsedHours, setReportElapsedHours] = useState(0);
  const [timerResetKeys, setTimerResetKeys] = useState<Record<string, number>>({});

  useEffect(() => {
    dispatch(fetchTeam({ page: 1, limit: 100 }));
    dispatch(fetchSprints({ page: 1, limit: 100 }));
    dispatch(fetchProjects({ page: 1, limit: 100 }));
    dispatch(fetchMilestones({ page: 1, limit: 100 }));
  }, [dispatch]);

  useEffect(() => {
    const timer = setTimeout(() => {
      dispatch(fetchTasks({ page: currentPage, limit: rowsPerPage, search: searchText, archived: isArchiveView }));
    }, 500);
    return () => clearTimeout(timer);
  }, [dispatch, currentPage, rowsPerPage, searchText, isArchiveView]);

  const handleOpenModal = (task?: any) => {
    if (task) {
      reset({
        ...task,
        projectId: task.project?.id || task.projectId || "",
        milestoneId: task.milestone?.id || task.milestoneId || "",
        sprintId: task.sprint?.id || task.sprintId || "",
        assignees: task.assignees?.length
          ? task.assignees.map((a: any) => typeof a === 'string' ? a : a.id)
          : (task.assignedDeveloperId ? [task.assignedDeveloperId] : []),
        reviewerId: task.reviewer?.id || task.reviewerId || "",
        startDate: task.startDate ? new Date(task.startDate).toISOString().split('T')[0] : "",
        dueDate: task.dueDate ? new Date(task.dueDate).toISOString().split('T')[0] : "",
        completedDate: task.completedDate ? new Date(task.completedDate).toISOString().split('T')[0] : "",
        status: task.status || "TODO",
        priority: task.priority || "Medium",
        storyPoints: task.storyPoints || 0,
        progressPercentage: task.progressPercentage || 0,
        labels: task.labels || [],
        subtasks: task.subtasks || [],
        estimatedHours: task.estimatedHours || 0,
        actualHours: task.actualHours || 0,
      });
      const attachment = task.attachments?.[0];
      setSelectedFileName(attachment?.originalName || attachment?.fileName || (typeof attachment === 'string' ? attachment : ""));
    } else {
      reset({
        id: undefined,
        title: "",
        description: "",
        projectId: "",
        milestoneId: "",
        sprintId: "",
        assignees: [],
        reviewerId: "",
        startDate: "",
        dueDate: "",
        completedDate: "",
        priority: "Medium",
        estimatedHours: 0,
        actualHours: 0,
        storyPoints: 0,
        progressPercentage: 0,
        labels: [],
        status: "TODO",
        attachments: [],
        comments: [],
        subtasks: []
      });
      setSelectedFileName("");
    }
    openModal();
  };

  const handleCloseModal = () => {
    reset({});
    setNewSubtask("");
    setNewLabel("");
    setSelectedFileName("");
    setSelectedFile(null);
    closeModal();
  };

  const handleSaveTask = (data: Partial<Task>) => {
    if (!data.assignees || data.assignees.length === 0) {
      setError("assignees", { type: "manual", message: "At least one assignee must be selected" });
      return;
    }
    const payload = { ...data };

    if (payload.assignees && payload.assignees.length > 0) {
      (payload as any).assignedDeveloperId = payload.assignees[0];
    }

    const currentLabels = [...formLabels];
    if (newLabel.trim() && !currentLabels.includes(newLabel.trim())) {
      currentLabels.push(newLabel.trim());
    }

    payload.labels = currentLabels;
    payload.subtasks = formSubtasks;

    const selectedSprint = sprints.find((s: any) => s.id === payload.sprintId);
    if (selectedSprint) {
      if ((selectedSprint as any).projectId) {
        payload.projectId = (selectedSprint as any).projectId;
      }
      payload.milestoneId = (selectedSprint as any).milestoneId;
    }

    if ((payload.status as any) === "To Do") payload.status = "TODO" as any;
    else if ((payload.status as any) === "In Progress") payload.status = "IN_PROGRESS" as any;
    else if (payload.status) payload.status = (payload.status as string).toUpperCase() as any;

    if (payload.priority) payload.priority = (payload.priority as string).toUpperCase() as any;

    let finalPayload: any = payload;

    if (selectedFile) {
      const formData = new FormData();
      Object.keys(payload).forEach(key => {
        const val = (payload as any)[key];
        if (val !== undefined && val !== null && val !== "") {
          if (typeof val === 'object' && !(val instanceof Date)) {
            formData.append(key, JSON.stringify(val));
          } else {
            formData.append(key, String(val));
          }
        }
      });
      formData.append('files', selectedFile);
      finalPayload = formData;
    }

    if (payload.id) {
      // Edit mode
      dispatch(updateTask({ id: payload.id, data: finalPayload })).then((resultAction: any) => {
        if (updateTask.fulfilled.match(resultAction)) {
          toast.success("Task updated successfully");
          dispatch(fetchTasks({ page: currentPage, limit: rowsPerPage, search: searchText }));
          handleCloseModal();
        } else {
          toast.error(typeof resultAction.payload === 'string' ? resultAction.payload : (resultAction.payload?.message || "Failed to update task"));
        }
      });
    } else {
      // Add mode
      dispatch(createTask(finalPayload)).then((resultAction: any) => {
        if (createTask.fulfilled.match(resultAction)) {
          toast.success("Task created successfully");
          dispatch(fetchTasks({ page: currentPage, limit: rowsPerPage, search: searchText }));
          handleCloseModal();
        } else {
          toast.error(typeof resultAction.payload === 'string' ? resultAction.payload : (resultAction.payload?.message || "Failed to create task"));
        }
      });
    }
  };

  const handleDeleteTask = (task: Task) => {
    setTaskToDelete(task);
    setIsDeleteModalOpen(true);
  };
  const closeDeleteModal = () => {
    setIsDeleteModalOpen(false);
    setTaskToDelete(null);
  };

  const handleViewTask = (task: Task) => {
    setSelectedTask(task);
    setIsViewModalOpen(true);
  };

  const closeViewModal = () => {
    setIsViewModalOpen(false);
    setSelectedTask(null);
  };

  const handleTimerStop = (task: Task, elapsedHours: number) => {
    setReportTask(task);
    setReportElapsedHours(elapsedHours);
    setIsReportModalOpen(true);
  };

  const handleReportSubmit = (data: DailyReportFormData) => {
    if (!authUser) {
      toast.error("User not found");
      return;
    }

    let formattedStatus: any = data.status;
    if (formattedStatus === "To Do") formattedStatus = "TODO";
    else if (formattedStatus === "In Progress") formattedStatus = "IN_PROGRESS";
    else if (formattedStatus) formattedStatus = (formattedStatus as string).toUpperCase();

    const reportData = {
      taskId: data.taskId,
      hours: data.hours,
      minutes: data.minutes,
      progressPercentage: data.progressPercentage,
      workDoneToday: data.workDoneToday,
      planForTomorrow: data.tomorrowPlan,
      hasBlockers: data.hasBlockers,
      blockers: data.hasBlockers ? data.blockers : "",
      comments: data.taskComments,
      status: formattedStatus
    };

    dispatch(createReport(reportData)).then((res) => {
      if (res.meta.requestStatus === 'fulfilled') {
        localStorage.removeItem(`task-timer-${data.taskId}`);
        window.dispatchEvent(new Event('task-timer-updated'));
        setTimerResetKeys(prev => ({ ...prev, [data.taskId]: Date.now() }));

        if (reportTask && formattedStatus && formattedStatus !== reportTask.status) {
          dispatch(updateTask({ id: data.taskId, data: { status: formattedStatus } })).then(() => {
            dispatch(fetchTasks({ page: currentPage, limit: rowsPerPage, search: searchText }));
          });
        } else {
          dispatch(fetchTasks({ page: currentPage, limit: rowsPerPage, search: searchText }));
        }

        setIsReportModalOpen(false);
      } else {
        const errorMsg = typeof res.payload === 'string' ? res.payload : "Failed to submit report";
        toast.error(errorMsg);
      }
    });
  };

  const confirmDelete = () => {
    if (taskToDelete) {
      dispatch(deleteTask(taskToDelete.id)).then((resultAction: any) => {
        if (deleteTask.fulfilled.match(resultAction)) {
          toast.success("Task deleted successfully");
          dispatch(fetchTasks({ page: currentPage, limit: rowsPerPage, search: searchText, archived: isArchiveView }));
        } else {
          toast.error(typeof resultAction.payload === 'string' ? resultAction.payload : (resultAction.payload?.message || "Failed to delete task"));
        }
      });
    }
    closeDeleteModal();
  };

  const handleArchiveTask = (task: Task) => {
    setTaskToArchive(task);
    setIsArchiveModalOpen(true);
  };

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

  const confirmArchive = async () => {
    if (!taskToArchive) return;
    const resultAction = await dispatch(toggleArchiveTask(taskToArchive.id));
    if (toggleArchiveTask.fulfilled.match(resultAction)) {
      toast.success("Task archived successfully");
      closeArchiveModal();
      dispatch(fetchTasks({ page: currentPage, limit: rowsPerPage, search: searchText, archived: isArchiveView }));
    } else {
      toast.error("Failed to archive task");
    }
  };

  const handleUndoArchiveTask = (task: Task) => {
    setTaskToUndoArchive(task);
    setIsUndoArchiveModalOpen(true);
  };

  const closeUndoArchiveModal = () => {
    setIsUndoArchiveModalOpen(false);
    setTaskToUndoArchive(null);
  };

  const confirmUndoArchive = async () => {
    if (!taskToUndoArchive) return;
    const resultAction = await dispatch(toggleArchiveTask(taskToUndoArchive.id));
    if (toggleArchiveTask.fulfilled.match(resultAction)) {
      toast.success("Task un-archived successfully");
      closeUndoArchiveModal();
      dispatch(fetchTasks({ page: currentPage, limit: rowsPerPage, search: searchText, archived: isArchiveView }));
    } else {
      toast.error("Failed to un-archive task");
    }
  };

  const handleAddSubtask = () => {
    if (newSubtask.trim()) {
      const subtask: Subtask = {
        id: `S-${Date.now()}`,
        title: newSubtask.trim(),
        isCompleted: false
      };
      setValue("subtasks", [...formSubtasks, subtask]);
      setNewSubtask("");
    }
  };

  const handleToggleSubtask = (subtaskId: string) => {
    const updatedSubtasks = formSubtasks.map(s =>
      s.id === subtaskId ? { ...s, isCompleted: !s.isCompleted } : s
    );
    setValue("subtasks", updatedSubtasks);
  };

  const handleAddLabel = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter' && newLabel.trim()) {
      e.preventDefault();
      if (!formLabels.includes(newLabel.trim())) {
        setValue("labels", [...formLabels, newLabel.trim()]);
      }
      setNewLabel("");
    }
  };

  const removeLabel = (label: string) => {
    setValue("labels", formLabels.filter(l => l !== label));
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case "Completed": return "bg-[#2563EB]/10 text-[#2563EB]";
      case "In Progress": return "bg-[#b446e5]/10 text-[#b446e5]";
      case "Review": return "bg-[#F97316]/10 text-[#F97316]";
      case "Testing": return "bg-indigo-100 text-indigo-700";
      case "Blocked": return "bg-[#DC2626]/10 text-[#DC2626]";
      case "Hold": return "bg-orange-100 text-orange-600";
      case "To Do": return "bg-[#6b7280]/10 text-[#6b7280]"
      default: return "bg-gray-100 text-gray-700";
    }
  };

  const getPriorityColor = (priority: string) => {
    switch (priority) {
      case "Critical": return "text-[#EA580C] bg-[#EA580C]/10";
      case "High": return "text-[#DC2626] bg-[#DC2626]/10";
      case "Medium": return "text-[#F59E0B] bg-[#F59E0B]/10";
      case "Low": return "text-[#22C55E] bg-[#22C55E]/10";
      default: return "text-gray-600 bg-gray-50";
    }
  };

  const columns = [
    {
      name: 'S.No',
      selector: (row: Task, index?: number) => (index || 0) + 1 + (currentPage - 1) * rowsPerPage,
      sortable: false,
      width: '70px',
      cell: (row: Task, index?: number) => (
        <div data-th="S.No" className="mobile-cell">
          <span className="text-sm font-medium text-gray-500">
            {(index || 0) + 1 + (currentPage - 1) * rowsPerPage}
          </span>
        </div>
      )
    },
    {
      name: 'Task ID',
      selector: (row: Task) => row.id,
      sortable: true,
      minWidth: "120px",
      cell: (row: Task) => (
        <div data-th="Task ID" className="mobile-cell">
          <div className="text-gray-500 font-medium mb-1">{row.id}</div>
          <span className={`text-xs px-2 py-0.5 rounded ${getPriorityColor(row.priority)}`}>
            {row.priority}
          </span>
        </div>
      )
    },
    {
      name: 'Task Detail',
      selector: (row: Task) => row.title,
      sortable: true,
      grow: 2,
      minWidth: "220px",
      cell: (row: Task) => {
        const sprint = sprints.find(s => s.id === row.sprintId);
        const completedSubtasks = (row.subtasks || []).filter(s => s.isCompleted).length;
        return (
          <div data-th="Task Detail" className="mobile-cell">
            <div className="md:font-medium text-gray-600 md:text-gray-900 mb-1">{row.title}</div>
            <div className="text-sm text-gray-500 mb-2">{sprint?.name || row.sprintId}</div>
            <div className="flex items-center gap-3 text-xs text-gray-400">
              {row.subtasks.length > 0 && (
                <div className="flex items-center gap-1">
                  <AlignLeft size={14} />
                  <span>{completedSubtasks}/{row.subtasks.length}</span>
                </div>
              )}
              {(row.comments || []).length > 0 && (
                <div className="flex items-center gap-1">
                  <MessageSquare size={14} />
                  <span>{(row.comments || []).length}</span>
                </div>
              )}
              {(row.attachments || []).length > 0 && (
                <div className="flex items-center gap-1">
                  <Paperclip size={14} />
                  <span>{(row.attachments || []).length}</span>
                </div>
              )}
            </div>
          </div>
        );
      }
    },
    {
      name: 'Time Tracker',
      center: true,
      minWidth: "140px",
      cell: (row: Task) => (
        <div data-th="Time Tracker" className="mobile-cell flex justify-center">
          {row.status?.toUpperCase() === 'COMPLETED' ? (
            <span className="text-gray-400 text-xs">Completed</span>
          ) : isDevOrMember ? (
            <TaskTimer
              key={`${row.id}-${timerResetKeys[row.id] || 0}`}
              taskId={row.id}
              projectId={row.projectId || ''}
              onStop={(elapsed) => handleTimerStop(row, elapsed)}
              disabled={isReportModalOpen && reportTask?.id === row.id}
            />
          ) : (
            <span className="text-gray-400 text-xs">N/A</span>
          )}
        </div>
      )
    },
    {
      name: 'Assigned Developer',
      minWidth: "140px",
      cell: (row: Task) => {
        const assignedUsers = team.filter(u => row.assignees?.includes(u.id));
        return (
          <div data-th="Assigned Developer" className="mobile-cell text-gray-600 text-sm">
            {row.assignedDeveloper ? (
              <span>{[row.assignedDeveloper.firstName, row.assignedDeveloper.lastName].filter(Boolean).join(' ')}</span>
            ) : assignedUsers.length > 0 ? (
              <span>{assignedUsers.map(u => [u.firstName || u.name, u.lastName].filter(Boolean).join(' ')).join(', ')}</span>
            ) : (
              <span>-</span>
            )}
          </div>
        );
      }
    },
    {
      name: 'Due Date',
      minWidth: "180px",
      selector: (row: Task) => row.dueDate,
      sortable: true,
      cell: (row: Task) => (
        <div data-th="Due Date" className="mobile-cell text-gray-600 text-sm">
          <div className="flex items-center gap-1.5">
            <Clock size={14} className="text-gray-400" />
            {row.dueDate}
          </div>
          <div className="mt-1 text-xs text-gray-400">
            {row.actualHours} / {row.estimatedHours} hrs
          </div>
        </div>
      )
    },
    {
      name: 'Status',
      selector: (row: Task) => row.status,
      sortable: true,
      minWidth: "140px",
      cell: (row: Task) => (
        <div data-th="Status" className="mobile-cell">
          <span className={`rounded-md px-3 py-1.5 text-sm font-normal ${getStatusColor(row.status)}`}>
            {row.status}
          </span>
        </div>
      )
    }
  ];

  if (canView || canEdit || canDelete) {
    columns.push({
      name: 'Action',
      center: true,
      minWidth: "160px",
      cell: (row: Task) => (
        <div data-th="Action" className="mobile-cell w-full sm:w-auto">
          <div className="flex justify-start sm:justify-center items-center gap-2">
            {!isArchiveView ? (
              <>
                {canView && (
                  <span
                    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={() => handleViewTask(row)}
                    title="View"
                  >
                    <Eye size={16} />
                  </span>
                )}
                {canEdit && (
                  <span
                    onClick={() => handleOpenModal(row)}
                    className="cursor-pointer 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"
                    title="Edit"
                  >
                    <Pencil size={14} />
                  </span>
                )}
                {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={() => handleArchiveTask(row)}
                    title="Archive Task"
                  >
                    <Archive size={16} />
                  </button>
                )}
                {canDelete && (
                  <span
                    onClick={() => handleDeleteTask(row)}
                    className="cursor-pointer w-8 h-8 rounded-md bg-red-500/10 flex items-center justify-center text-red-600 hover:bg-red-500/20 transition-colors"
                    title="Delete"
                  >
                    <Trash2 size={14} />
                  </span>
                )}
              </>
            ) : (
              <>
                {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={() => handleUndoArchiveTask(row)}
                    title="Undo Archive"
                  >
                    <Undo2 size={16} />
                  </button>
                )}
              </>
            )}
          </div>
        </div>
      ),
    } as any);
  }

  const filteredTasks = tasks.filter(
    (task) =>
      task.title?.toLowerCase().includes(searchText.toLowerCase()) ||
      task.id?.toLowerCase().includes(searchText.toLowerCase())
  );

  return (
    <div className="min-h-screen">
      <div className="mx-auto max-w-[1500px] space-y-6">
        <div className="flex flex-wrap items-center justify-between gap-4 mb-6">
          <div className="flex flex-col gap-2">
            <div>
              <h1 className="text-xl lg:text-2xl font-medium text-brand-950">Task Management</h1>
              <p className="text-sm text-gray-500 mt-1">Manage project tasks and assignments</p>
            </div>

            <div className="flex items-center gap-1 bg-gray-100 p-1 rounded-lg w-max mt-2">
              <button
                onClick={() => setIsArchiveView(false)}
                className={`px-4 py-2 text-sm font-medium rounded-md transition-all ${!isArchiveView ? 'bg-white shadow-theme-xs text-brand-950' : 'text-gray-500 hover:text-gray-700'}`}
              >
                Active
              </button>
              <button
                onClick={() => setIsArchiveView(true)}
                className={`px-4 py-2 text-sm font-medium rounded-md transition-all ${isArchiveView ? 'bg-white shadow-theme-xs text-brand-950' : 'text-gray-500 hover:text-gray-700'}`}
              >
                Archived
              </button>
            </div>
          </div>
          {canCreate && (
            <button
              onClick={() => handleOpenModal()}
              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 bg-brand-950 text-white shadow-theme-xs hover:text-brand-950 hover:bg-yellow-500"
            >
              <svg className="w-5 h-5 fill-current" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg">
                <path fillRule="evenodd" clipRule="evenodd" d="M9 17a1 1 0 102 0v-6h6a1 1 0 100-2h-6V3a1 1 0 10-2 0v6H3a1 1 0 000 2h6v6z" />
              </svg>
              <span className="hidden lg:inline-block">Create Task</span>
            </button>
          )}
        </div>

        {/* Tasks 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);
                      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 tasks..."
                    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
                key={`table-${rowsPerPage}`}
                columns={columns}
                data={filteredTasks}
                pagination
                paginationResetDefaultPage={resetPaginationToggle}
                paginationServer
                paginationTotalRows={total}
                paginationPerPage={rowsPerPage}
                paginationComponentOptions={{ noRowsPerPage: true }}
                onChangePage={(page) => setCurrentPage(page)}
                onChangeRowsPerPage={(newPerPage, page) => {
                  setRowsPerPage(newPerPage);
                  setCurrentPage(page);
                }}
                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>

        {/* Add/Edit 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">
              <h4 className="mb-2 text-xl lg:text-2xl font-semibold text-brand-950">
                {taskId ? "Edit Task" : "Create New Task"}
              </h4>
              {/* <p className="mb-6 text-sm text-gray-500 lg:mb-7">
                {taskId && <span>{taskId}</span>}
              </p> */}
            </div>

            <form onSubmit={handleSubmit(handleSaveTask)} 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">
                {/* Main Content Column */}
                <div className="col-span-2">
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Task Title</label>
                  <input
                    type="text"
                    {...register("title", { required: "Task Title 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.title ? 'border-red-500' : 'border-gray-300'}`}
                    placeholder="What needs to be done?"
                  />
                  {errors.title && <p className="text-red-500 text-xs mt-1">{errors.title.message as string}</p>}
                </div>

                <div className="col-span-2">
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Description</label>
                  <textarea
                    {...register("description", { required: "Description 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-[120px] ${errors.description ? 'border-red-500' : 'border-gray-300'}`}
                    placeholder="Add more details about this task..."
                  />
                  {errors.description && <p className="text-red-500 text-xs mt-1">{errors.description.message as string}</p>}
                </div>



                {/* Sidebar Column */}
                <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" })}
                      value={watchProjectId || ""}
                      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'}`}
                      onChange={(e) => {
                        register("projectId").onChange(e);
                        setValue("milestoneId", "");
                        setValue("sprintId", "");

                        const selectedId = e.target.value;
                        const proj = activeProjects.find(p => p.id === selectedId);
                        if (proj && (!proj.milestones || proj.milestones.length === 0)) {
                          toast.error("No active milestones found for this project");
                        }
                      }}
                    >
                      <option value="" disabled>Select Project</option>
                      {activeProjects.map(p => <option key={p.id} value={p.id}>{p.title || 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">Milestone</label>
                  <div className="relative">
                    <select
                      {...register("milestoneId")}
                      value={watchMilestoneId || ""}
                      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.milestoneId ? 'border-red-500' : 'border-gray-300'}`}
                      onChange={(e) => {
                        register("milestoneId").onChange(e);
                        setValue("sprintId", "");

                        const selectedId = e.target.value;
                        const miles = activeMilestones.find((m: any) => m.id === selectedId);
                        if (miles && (!miles.sprints || miles.sprints.length === 0)) {
                          toast.error("No active sprints found for this milestone");
                        }
                      }}
                    >
                      <option value="">Select Milestone</option>
                      {activeMilestones.map((m: any) => <option key={m.id} value={m.id}>{m.title || m.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>
                </div>

                <div className="col-span-2 lg:col-span-1">
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Sprint</label>
                  <div className="relative">
                    <select
                      {...register("sprintId", { required: "Sprint is required" })}
                      value={watch("sprintId") || ""}
                      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.sprintId ? 'border-red-500' : 'border-gray-300'}`}
                    >
                      <option value="" disabled>Select Sprint</option>
                      {activeSprints.map((s: any) => <option key={s.id} value={s.id}>{s.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.sprintId && <p className="text-red-500 text-xs mt-1">{errors.sprintId.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">Status</label>
                  <div className="relative">
                    <select
                      {...register("status")}
                      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 border-gray-300 outline-none"
                    >
                      <option value="To Do">To Do</option>
                      <option value="In Progress">In Progress</option>
                      <option value="Review">Review</option>
                      <option value="Testing">Testing</option>
                      <option value="Completed">Completed</option>
                      <option value="Blocked">Blocked</option>
                      <option value="Hold">Hold</option>
                      <option value="Pending">Pending</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>
                </div>

                <div className="col-span-2 lg:col-span-1">
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Priority</label>
                  <div className="relative">
                    <select
                      {...register("priority")}
                      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 border-gray-300 outline-none"
                    >
                      <option value="Low">Low</option>
                      <option value="Medium">Medium</option>
                      <option value="High">High</option>
                      <option value="Critical">Critical</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>
                </div>

                <div className="col-span-2 lg:col-span-1">
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Due Date</label>
                  <div className="relative">
                    <input
                      type="date"
                      min={taskStartDate || ""}
                      {...register("dueDate", { required: "Due 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.dueDate ? '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.dueDate && <p className="text-red-500 text-xs mt-1">{errors.dueDate.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">Start Date</label>
                  <div className="relative">
                    <input
                      type="date"
                      {...register("startDate")}
                      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 border-gray-300 outline-none"
                    />
                    <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="col-span-2 lg:col-span-1">
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Completed Date</label>
                  <div className="relative">
                    <input
                      type="date"
                      min={taskStartDate || ""}
                      {...register("completedDate")}
                      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 border-gray-300 outline-none"
                    />
                    <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="col-span-2 lg:col-span-1">
                  <label className="mb-1.5 block text-sm font-medium text-gray-700" title="Estimated Hours">Est. Hrs</label>
                  <input
                    type="number"
                    min="0"
                    {...register("estimatedHours", { 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 border-gray-300 outline-none"
                  />
                </div>
                <div className="col-span-2 lg:col-span-1">
                  <label className="mb-1.5 block text-sm font-medium text-gray-700" title="Actual Hours">Act. Hrs</label>
                  <input
                    type="number"
                    min="0"
                    {...register("actualHours", { 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 border-gray-300 outline-none"
                  />
                </div>

                <div className="col-span-2 lg:col-span-1">
                  <label className="mb-1.5 block text-sm font-medium text-gray-700" title="Story Points">Story Pts</label>
                  <input
                    type="number"
                    min="0"
                    {...register("storyPoints", { 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 border-gray-300 outline-none"
                  />
                </div>

                <div className="col-span-2 lg:col-span-1">
                  <label className="mb-1.5 block text-sm font-medium text-gray-700" title="Progress (%)">Progress (%)</label>
                  <input
                    type="number"
                    min="0"
                    max="100"
                    {...register("progressPercentage", { 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 border-gray-300 outline-none"
                  />
                </div>

                <div className="col-span-2">
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Task File</label>
                  <label className="flex cursor-pointer items-center justify-between gap-3 rounded-lg border border-dashed border-gray-300 bg-gray-50 px-4 py-3 text-sm shadow-theme-xs transition">
                    <span className="truncate text-gray-600">{selectedFileName || "Choose a file to upload"}</span>
                    <span className="rounded-md bg-brand-950 px-3 py-1.5 text-sm font-normal text-white">Browse</span>
                    <input
                      type="file"
                      className="sr-only"
                      onChange={(e) => {
                        const file = e.target.files?.[0];
                        if (file) {
                          setSelectedFileName(file.name);
                          setSelectedFile(file);
                        } else {
                          setSelectedFileName("");
                          setSelectedFile(null);
                        }
                      }}
                    />
                  </label>
                  {selectedFileName && (
                    <p className="mt-2 text-xs text-gray-500">Selected file: {selectedFileName}</p>
                  )}
                </div>

                <div className="col-span-2">
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Assignees</label>
                  <MultiSelect
                    options={team
                      .filter(member => member.status?.toUpperCase() === 'ACTIVE' && !['admin', 'project-manager', 'team-leader'].includes(member.role))
                      .map(member => ({
                        value: member.id,
                        label: `${member.name} (${member.role.replace(/-/g, ' ').replace(/\\b\\w/g, l => l.toUpperCase())})`
                      }))}
                    value={formAssignees}
                    onChange={(newTeam) => { setValue("assignees", newTeam); clearErrors("assignees"); }}
                    placeholder="Select assignees..."
                  />
                  {errors.assignees && <p className="text-red-500 text-xs mt-1">{errors.assignees.message as string}</p>}
                </div>

                <div className="col-span-2">
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Reviewer</label>
                  <div className="relative">
                    <select
                      {...register("reviewerId")}
                      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 border-gray-300 outline-none"
                    >
                      <option value="">Select Reviewer</option>
                      {team
                        .filter(member => member.status?.toUpperCase() === 'ACTIVE' && ['admin', 'project-manager', 'team-leader'].includes(member.role))
                        .map(member => (
                          <option key={member.id} value={member.id}>
                            {member.name} ({member.role.replace(/-/g, ' ').replace(/\\b\\w/g, l => l.toUpperCase())})
                          </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>
                </div>

                <div className="col-span-2">
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Labels</label>
                  <div className={`flex flex-wrap gap-1.5 ${formLabels.length ? "mb-1.5" : ""}`}>
                    {formLabels.map(label => (
                      <span key={label} className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-700 border border-gray-200">
                        {label}
                        <button type="button" onClick={() => removeLabel(label)} className="text-gray-400 hover:text-gray-600">
                          <X size={12} />
                        </button>
                      </span>
                    ))}
                  </div>
                  <input
                    type="text"
                    value={newLabel}
                    onChange={(e) => setNewLabel(e.target.value)}
                    onKeyDown={handleAddLabel}
                    placeholder="Type & press Enter..."
                    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 border-gray-300 outline-none"
                  />
                </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"
                >
                  {taskId ? "Save Changes" : "Create Task"}
                </button>
              </div>
            </form>
          </div>
        </Modal>

        {/* Delete Task 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 <span className="font-semibold text-gray-800">{taskToDelete?.title}</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 Task 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 Task</h3>
              <p className="text-sm text-gray-500 mb-8 leading-relaxed">
                Are you sure you want to archive <span className="font-semibold text-gray-800">{taskToArchive?.title}</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 Task 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 Task</h3>
              <p className="text-sm text-gray-500 mb-8 leading-relaxed">
                Are you sure you want to un-archive <span className="font-semibold text-gray-800">{taskToUndoArchive?.title}</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>


        {/* Daily Report Modal */}
        <DailyReportModal
          isOpen={isReportModalOpen}
          onClose={() => setIsReportModalOpen(false)}
          task={reportTask}
          elapsedHours={reportElapsedHours}
          onSubmit={handleReportSubmit}
        />

        {/* View Task Modal */}
        {selectedTask && (
          <Modal isOpen={isViewModalOpen} onClose={closeViewModal} 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">
                <h4 className="mb-2 text-xl lg:text-2xl font-semibold text-brand-950">
                  {selectedTask.title}
                </h4>
                {/* <p className="mb-6 text-sm text-gray-500 lg:mb-7">
                  ID: {selectedTask.id} | Priority: <span className="font-medium capitalize text-gray-700">{selectedTask.priority}</span> | Project: {(selectedTask as any).project?.title || selectedTask.projectId || 'N/A'} | Sprint: {(selectedTask as any).sprint?.name || selectedTask.sprintId || 'N/A'}
                </p> */}
              </div>

              <div className="px-2 space-y-6 lg:space-y-5">
                <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-4">
                  <div className="bg-gray-50 p-4 rounded-lg border border-gray-200 lg:col-span-1">
                    <p className="mb-1.5 block text-sm font-normal text-gray-500">Status</p>
                    <p className={`font-medium ${selectedTask.status === "IN_PROGRESS" ? "text-[#b446e5]" :
                      selectedTask.status === "COMPLETED" ? "text-[#2563EB]" :
                        selectedTask.status === "REVIEW" ? "text-[#F97316]" :
                          "text-gray-600"
                      }`}>
                      {selectedTask.status}
                    </p>
                  </div>
                  <div className="bg-gray-50 p-4 rounded-lg border border-gray-200 lg:col-span-1">
                    <p className="mb-1.5 block text-sm font-normal text-gray-500">Story Points</p>
                    <p className="font-medium text-gray-800">{(selectedTask as any).storyPoints || 0}</p>
                  </div>
                  <div className="bg-gray-50 p-4 rounded-lg border border-gray-200 lg:col-span-1">
                    <p className="mb-1.5 block text-sm font-normal text-gray-500">Hours (Act/Est)</p>
                    <p className="font-medium text-gray-800">{(selectedTask as any).actualHours || 0} / {(selectedTask as any).estimatedHours || 0}</p>
                  </div>
                  <div className="bg-gray-50 p-4 rounded-lg border border-gray-200 sm:col-span-2 lg:col-span-2">
                    <p className="mb-1.5 block text-sm font-normal text-gray-500">Progress</p>
                    <div className="flex items-center gap-3 min-h-6">
                      <div className="flex-1 bg-gray-200 rounded-full h-2.5">
                        <div className="bg-green-500 h-2.5 rounded-full" style={{ width: `${(selectedTask as any).progressPercentage || 0}%` }}></div>
                      </div>
                      <span className="text-sm font-medium text-gray-700">{(selectedTask as any).progressPercentage || 0}%</span>
                    </div>
                  </div>
                </div>

                <div className="bg-gray-50 p-4 rounded-lg border border-gray-200">
                  <p className="mb-1.5 block text-sm font-normal text-gray-500">Assignees ({selectedTask.assignees?.length || 0})</p>
                  <div className="flex flex-wrap gap-2 mt-2">
                    {selectedTask.assignees && selectedTask.assignees.length > 0 ? (
                      selectedTask.assignees.map((userId: string, idx: number) => {
                        let user = team.find((u: any) => u.id === userId);
                        if (!user && (selectedTask as any).assignedDeveloper?.id === userId) {
                          user = (selectedTask as any).assignedDeveloper;
                        }
                        return (
                          <span key={idx} className="px-3 py-1 bg-white border border-gray-200 rounded-full text-sm font-medium text-gray-700">
                            {user ? [user.firstName || user.name, user.lastName].filter(Boolean).join(' ') : "Unknown User"}
                          </span>
                        );
                      })
                    ) : (
                      <span className="text-sm text-gray-500 italic">Unassigned</span>
                    )}
                  </div>
                </div>

                <div>
                  <h5 className="mb-4 text-lg font-medium text-gray-800">Task Details</h5>
                  <div className="bg-white border border-gray-200 rounded-lg p-4 space-y-4">
                    <div className="flex items-center gap-3 w-full">
                      <div className="min-w-0 w-full">
                        <p className="text-sm text-gray-500 font-normal">Description</p>
                        <p className="text-sm font-medium text-gray-800 mt-1.5 break-all whitespace-pre-wrap">{selectedTask.description || "No description provided."}</p>
                      </div>
                    </div>
                    <div className="grid grid-cols-3 gap-4 pt-4 border-t border-gray-100">
                      <div>
                        <p className="mb-1.5 block text-sm font-normal text-gray-500">Start Date</p>
                        <p className="text-sm font-medium text-gray-800">{(selectedTask as any).startDate || "N/A"}</p>
                      </div>
                      <div>
                        <p className="mb-1.5 block text-sm font-normal text-gray-500">Due Date</p>
                        <p className="text-sm font-medium text-gray-800">{(selectedTask as any).dueDate || "N/A"}</p>
                      </div>
                      <div>
                        <p className="mb-1.5 block text-sm font-normal text-gray-500">Completed Date</p>
                        <p className="text-sm font-medium text-gray-800">{(selectedTask as any).completedDate ? (selectedTask as any).completedDate.split('T')[0] : "N/A"}</p>
                      </div>
                    </div>
                  </div>
                </div>

                {/* {selectedTask.subtasks && selectedTask.subtasks.length > 0 && (
                  <div>
                    <h5 className="mb-4 text-lg font-medium text-gray-800">Subtasks</h5>
                    <div className="bg-white border border-gray-200 rounded-lg p-4 space-y-2">
                      {selectedTask.subtasks.map((subtask, index) => (
                        <div key={index} className="flex items-center gap-3">
                          {subtask.isCompleted ? <CheckSquare size={16} className="text-green-500" /> : <Square size={16} className="text-gray-300" />}
                          <span className={`text-sm ${subtask.isCompleted ? 'text-gray-400 line-through' : 'text-gray-800'}`}>{subtask.title}</span>
                        </div>
                      ))}
                    </div>
                  </div>
                )} */}

                {selectedTask.labels && selectedTask.labels.length > 0 && (
                  <div>
                    <h5 className="mb-4 text-lg font-medium text-gray-800">Labels</h5>
                    <div className="flex flex-wrap gap-2">
                      {selectedTask.labels.map((label, index) => (
                        <span key={index} className="px-2 py-1 text-xs font-medium bg-brand-950/10 text-brand-950 rounded-md">
                          {label}
                        </span>
                      ))}
                    </div>
                  </div>
                )}

                {selectedTask.attachments && selectedTask.attachments.length > 0 && (
                  <div>
                    <h5 className="mb-4 text-lg font-medium text-gray-800">Attachments</h5>
                    <div className="flex flex-col gap-2">
                      {selectedTask.attachments.map((attachment: any, index: number) => {
                        const fileName = attachment?.originalName || attachment?.fileName || (typeof attachment === 'string' ? attachment : `Attachment ${index + 1}`);
                        const url = attachment?.publicUrl || attachment?.url || (typeof attachment === 'string' ? attachment : '#');
                        const fullUrl = url.startsWith('http') ? url : `${process.env.NEXT_PUBLIC_API_URL || 'http://192.168.1.23:5000'}${url.startsWith('/') ? '' : '/'}${url}`;

                        return (
                          <a
                            key={index}
                            href={fullUrl}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="flex items-center gap-2 p-3 bg-gray-50 border border-gray-200 rounded-lg hover:bg-gray-100 transition-colors w-fit"
                          >
                            <Paperclip size={16} className="text-gray-500" />
                            <span className="text-sm font-medium text-brand-950">{fileName}</span>
                          </a>
                        );
                      })}
                    </div>
                  </div>
                )}
              </div>
            </div>
          </Modal>
        )}
      </div>
    </div>
  );
}
