"use client";
import React, { useState, useEffect } from "react";
import { Eye, Trash2, ChevronDown, ChevronLeft, ChevronRight, X, Pencil, Plus, Search, Archive, Undo2 } from "lucide-react";
import { Milestone } from "@/types";
import { CalendarDaysIcon } from "@heroicons/react/24/outline";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { fetchMilestones, createMilestone, updateMilestone, deleteMilestone, toggleArchiveMilestone } from "@/store/slices/milestoneSlice";
import { fetchProjects } from "@/store/slices/projectSlice";
import { fetchTeam } from "@/store/slices/teamSlice";
import DataTable from "react-data-table-component";
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";

export default function MilestonesManagementPage() {
  const dispatch = useAppDispatch();
  const { milestones, total, isLoading } = useAppSelector((state) => state.milestones);
  const projects = useAppSelector((state) => state.projects.projects);
  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('milestone.view');
  const canEdit = isAdmin || hasPermission('milestone.update');
  const canDelete = isAdmin || hasPermission('milestone.delete');
  const canCreate = isAdmin || hasPermission('milestone.create');

  const { isOpen, openModal, closeModal } = useModal();
  const { register, handleSubmit, reset, watch, setValue, setError, clearErrors, formState: { errors } } = useForm<Milestone>({
    defaultValues: {
      status: "Pending",
      assignedTeam: [],
    }
  });
  const formId = watch("id");
  const formAssignedTeam = watch("assignedTeam") || [];
  const formStartDate = watch("startDate");

  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
  const [milestoneToDelete, setMilestoneToDelete] = useState<Milestone | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);

  const [searchText, setSearchText] = useState("");
  const [rowsPerPage, setRowsPerPage] = useState(10);
  const [currentPage, setCurrentPage] = useState(1);
  const [resetPaginationToggle, setResetPaginationToggle] = useState(false);
  const [isArchiveView, setIsArchiveView] = useState(false);
  const [isArchiveModalOpen, setIsArchiveModalOpen] = useState(false);
  const [milestoneToArchive, setMilestoneToArchive] = useState<Milestone | null>(null);
  const [isUndoArchiveModalOpen, setIsUndoArchiveModalOpen] = useState(false);
  const [milestoneToUndoArchive, setMilestoneToUndoArchive] = useState<Milestone | null>(null);
  const [isViewModalOpen, setIsViewModalOpen] = useState(false);
  const [selectedMilestone, setSelectedMilestone] = useState<Milestone | null>(null);
  const [usersByRole, setUsersByRole] = useState<any>({ projectManagers: [], teamLeaders: [], teamMembers: [] });
  const [teamLoading, setTeamLoading] = useState(true);

  useEffect(() => {
    dispatch(fetchProjects({ page: 1, limit: 100 }));
    dispatch(fetchTeam({ page: 1, limit: 100 }));
  }, [dispatch]);
  useEffect(() => {
    const timer = setTimeout(() => {
      dispatch(fetchMilestones({ page: currentPage, limit: rowsPerPage, search: searchText, archived: isArchiveView }));
    }, 500);
    return () => clearTimeout(timer);
  }, [dispatch, currentPage, rowsPerPage, searchText, isArchiveView]);
  useEffect(() => {
    const fetchUsersByRole = async () => {
      try {
        setTeamLoading(true);
        const response = await axiosInstance.get('/api/users/users-by-role');
        if (response.data?.success) {
          setUsersByRole(response.data.data);
        }
      } catch (err) {
        console.error("Failed to fetch users by role", err);
      } finally {
        setTeamLoading(false);
      }
    };
    fetchUsersByRole();
  }, []);
  const handleOpenModal = (milestone?: Milestone) => {
    if (milestone) {
      reset(milestone);
    } else {
      reset({
        name: "",
        description: "",
        projectId: "",
        startDate: new Date().toISOString().split('T')[0],
        dueDate: "",
        assignedTeam: [],
        status: "Pending",
        trackProgress: 0,
      });
    }
    openModal();
  };
  const handleCloseModal = () => {
    reset();
    closeModal();
  };
  const handleSaveMilestone = async (data: Milestone) => {
    if (!data.assignedTeam || data.assignedTeam.length === 0) {
      setError("assignedTeam", { type: "manual", message: "At least one team member must be assigned" });
      return;
    }

    const payload = { ...data, status: data.status.toUpperCase() } as any;
    setIsSubmitting(true);

    try {
      if (data.id) {
        await dispatch(updateMilestone({ id: data.id, data: payload })).unwrap();
        toast.success("Milestone updated successfully");
      } else {
        await dispatch(createMilestone(payload)).unwrap();
        toast.success("Milestone created successfully");
      }
      dispatch(fetchMilestones({ page: currentPage, limit: rowsPerPage, search: searchText }));
      setIsSubmitting(false);
      handleCloseModal();
    } catch (error: any) {
      toast.error(error || "Failed to save milestone");
      setIsSubmitting(false);
    }
  };
  const handleDeleteMilestone = (milestone: Milestone) => {
    setMilestoneToDelete(milestone);
    setIsDeleteModalOpen(true);
  };
  const closeDeleteModal = () => {
    setIsDeleteModalOpen(false);
    setMilestoneToDelete(null);
  };
  const handleViewMilestone = (milestone: Milestone) => {
    setSelectedMilestone(milestone);
    setIsViewModalOpen(true);
  };
  const closeViewModal = () => {
    setIsViewModalOpen(false);
    setSelectedMilestone(null);
  };
  const confirmDelete = async () => {
    if (milestoneToDelete) {
      try {
        await dispatch(deleteMilestone(milestoneToDelete.id)).unwrap();
        dispatch(fetchMilestones({ page: currentPage, limit: rowsPerPage, search: searchText, archived: isArchiveView }));
        toast.success("Milestone deleted successfully");
        closeDeleteModal();
      } catch (error: any) {
        toast.error(error || "Failed to delete milestone");
        closeDeleteModal();
      }
    } else {
      closeDeleteModal();
    }
  };
  const handleArchiveMilestone = (milestone: Milestone) => {
    setMilestoneToArchive(milestone);
    setIsArchiveModalOpen(true);
  };
  const closeArchiveModal = () => {
    setIsArchiveModalOpen(false);
    setMilestoneToArchive(null);
  };
  const confirmArchive = async () => {
    if (milestoneToArchive) {
      try {
        await dispatch(toggleArchiveMilestone(milestoneToArchive.id)).unwrap();
        toast.success("Milestone archived successfully");
        closeArchiveModal();
      } catch (error: any) {
        toast.error(error || "Failed to archive milestone");
        closeArchiveModal();
      }
    }
  };
  const handleUndoArchiveMilestone = (milestone: Milestone) => {
    setMilestoneToUndoArchive(milestone);
    setIsUndoArchiveModalOpen(true);
  };
  const closeUndoArchiveModal = () => {
    setIsUndoArchiveModalOpen(false);
    setMilestoneToUndoArchive(null);
  };
  const confirmUndoArchive = async () => {
    if (milestoneToUndoArchive) {
      try {
        await dispatch(toggleArchiveMilestone(milestoneToUndoArchive.id)).unwrap();
        toast.success("Milestone un-archived successfully");
        closeUndoArchiveModal();
      } catch (error: any) {
        toast.error(error || "Failed to un-archive milestone");
        closeUndoArchiveModal();
      }
    }
  };
  const getStatusColor = (status: string) => {
    switch (status) {
      case "Completed": return "bg-[#2563EB]/10 text-[#2563EB]";
      case "Active": return "bg-[#22C55E]/10 text-[#22C55E]";
      case "Delayed": return "bg-[#EF4444]/10 text-[#EF4444]";
      case "On Hold": return "bg-orange-100 text-orange-600";
      case "Pending": return "bg-[#F59E0B]/10 text-[#F59E0B]";
      default: return "bg-slate-100 text-slate-600";
    }
  };

  const columns = [
    {
      name: "S.No.",
      sortable: false,
      cell: (row: Milestone, index: number) => (
        <div data-th="S.No." className="mobile-cell">
          <span className="text-gray-500">{(currentPage - 1) * rowsPerPage + index + 1}</span>
        </div>
      ),
    },
    {
      name: 'Milestone Name',
      selector: (row: Milestone) => row.name,
      sortable: true,
      minWidth: "180px",
      cell: (row: Milestone) => <div data-th="Milestone Name" className="mobile-cell"><span className="md:font-medium text-gray-600 md:text-gray-900">{row.name}</span></div>
    },
    {
      name: 'Project',
      selector: (row: Milestone) => row.projectId,
      sortable: true,
      minWidth: "140px",
      cell: (row: Milestone) => {
        const project = projects.find(p => p.id === row.projectId);
        return <div data-th="Project" className="mobile-cell"><span className="text-gray-600">{project?.name || row.projectId}</span></div>;
      }
    },
    {
      name: 'Duration',
      selector: (row: Milestone) => row.startDate,
      sortable: true,
      minWidth: "160px",
      cell: (row: Milestone) => (
        <div data-th="Duration" className="mobile-cell">
          <div className="text-gray-600 text-sm">
            <div>{row.startDate ? row.startDate.split('T')[0] : ''} to {row.dueDate ? row.dueDate.split('T')[0] : ''}</div>
          </div>
        </div>
      )
    },
    {
      name: 'Progress',
      selector: (row: Milestone) => row.trackProgress,
      sortable: true,
      minWidth: "180px",
      cell: (row: Milestone) => (
        <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.5 min-w-[60px] max-w-[100px]">
            <div
              className="bg-green-600 h-2.5 rounded-full"
              style={{ width: `${row.trackProgress}%` }}
            ></div>
          </div>
          <span className="text-sm text-gray-600">{row.trackProgress}%</span>
        </div>
      )
    },
    {
      name: 'Assigned Team',
      minWidth: "140px",
      cell: (row: Milestone) => {
        const assignedUsers = team.filter(u => row.assignedTeam?.includes(u.id));
        return (
          <div data-th="Assigned Team" className="mobile-cell">
            <div className="text-gray-600 text-sm">
              {row?.responsibleUsers && row?.responsibleUsers.length > 0 ? (
                row?.responsibleUsers?.map((ru: any) => [ru?.user?.firstName, ru?.user?.lastName].filter(Boolean)?.join(' '))?.join(', ')
              ) : assignedUsers?.length > 0 ? (
                assignedUsers?.map(u => [u?.firstName || u?.name, u?.lastName].filter(Boolean)?.join(' '))?.join(', ')
              ) : (
                "-"
              )}
            </div>
          </div>
        );
      }
    },
    {
      name: 'Status',
      selector: (row: Milestone) => row.status,
      sortable: true,
      minWidth: "140px",
      cell: (row: Milestone) => (
        <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: Milestone) => (
        <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="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={() => handleViewMilestone(row)}
                  >
                    <Eye size={18} />
                  </button>
                )}

                {canEdit && (
                  <span
                    className="cursor-pointer w-8 h-8 rounded-md bg-yellow-500/30 flex items-center justify-center text-[#c17916]"
                    onClick={() => handleOpenModal(row)}
                  >
                    <Pencil size={16} />
                  </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"
                    title="Archive"
                    onClick={() => handleArchiveMilestone(row)}
                  >
                    <Archive size={16} />
                  </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={() => handleDeleteMilestone(row)}
                  >
                    <Trash2 size={16} />
                  </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"
                    title="Un-Archive"
                    onClick={() => handleUndoArchiveMilestone(row)}
                  >
                    <Undo2 size={16} />
                  </button>
                )}
              </>
            )}
          </div>
        </div>
      )
    } as any);
  }

  const filteredMilestones = milestones;

  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">
            <h1 className="text-xl lg:text-2xl font-medium text-brand-950">Milestone Management</h1>
            {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 Milestone</span>
              </button>
            )}
          </div>

          <div className="flex space-x-1 bg-gray-100 p-1 rounded-lg w-fit">
            <button
              onClick={() => {
                setIsArchiveView(false);
                setCurrentPage(1);
              }}
              className={`px-4 py-2 text-sm font-medium rounded-md transition-colors ${!isArchiveView
                ? "bg-white text-gray-900 shadow-sm"
                : "text-gray-500 hover:text-gray-900 hover:bg-gray-50"
                }`}
            >
              Active
            </button>
            <button
              onClick={() => {
                setIsArchiveView(true);
                setCurrentPage(1);
              }}
              className={`px-4 py-2 text-sm font-medium rounded-md transition-colors ${isArchiveView
                ? "bg-black text-white shadow-sm"
                : "text-gray-500 hover:text-gray-900 hover:bg-gray-50"
                }`}
            >
              Archived
            </button>
          </div>

          {/* Milestones Table */}
          <div className="rounded-xl bg-white p-6 shadow-theme-md">
            <div className="md:border border-gray-200 md: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-400 -translate-y-1/2 pointer-events-none right-1.5 top-1/2">
                      <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" viewBox="0 0 24 24">
                        <path stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 9l6 6 6-6"></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"
                      value={searchText}
                      placeholder="Search milestones..."
                      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={filteredMilestones}
                  progressPending={isLoading}
                  pagination
                  paginationResetDefaultPage={resetPaginationToggle}
                  paginationServer
                  paginationTotalRows={total}
                  paginationPerPage={rowsPerPage}
                  onChangePage={(page) => setCurrentPage(page)}
                  onChangeRowsPerPage={(newPerPage, page) => {
                    setRowsPerPage(newPerPage);
                    setCurrentPage(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>

          {/* 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 mb-6 lg:mb-7">
                <h4 className="text-xl lg:text-2xl font-semibold text-brand-950">
                  {formId ? "Edit Milestone" : "Create New Milestone"}
                </h4>
              </div>

              <form onSubmit={handleSubmit(handleSaveMilestone)} className="px-2">
                <div className="grid grid-cols-1 gap-x-6 gap-y-5 lg:grid-cols-2">
                  <div className="col-span-1 lg:col-span-2">
                    <label className="mb-1.5 block text-sm font-medium text-gray-700">Milestone Name</label>
                    <input
                      type="text"
                      {...register("name", { required: "Milestone name 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.name ? 'border-red-500' : 'border-gray-300'}`}
                      placeholder="E.g. Phase 1: Core Features"
                    />
                    {errors.name && <p className="text-red-500 text-xs mt-1">{errors.name.message}</p>}
                  </div>

                  <div className="col-span-1 lg:col-span-2">
                    <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.filter(p => p.status?.toUpperCase() === 'ACTIVE').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}</p>}
                  </div>

                  <div className="col-span-1 lg:col-span-2">
                    <label className="mb-1.5 block text-sm font-medium text-gray-700">Description & Notes</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-[100px] ${errors.description ? 'border-red-500' : 'border-gray-300'}`}
                      placeholder="Describe the goals and notes for this milestone..."
                    />
                    {errors.description && <p className="text-red-500 text-xs mt-1">{errors.description.message}</p>}
                  </div>

                  <div className="relative col-span-2 lg:col-span-1">
                    <label className="mb-1.5 block text-sm font-medium text-gray-700">
                      Start Date
                    </label>

                    <input
                      type="date"
                      {...register("startDate", { required: "Start date is required" })}
                      onClick={(e) => e.currentTarget.showPicker?.()}
                      className={`h-11 w-full rounded-lg border appearance-none px-4 py-2.5 pr-10 text-sm shadow-theme-xs placeholder:text-gray-400 bg-transparent text-gray-800 outline-none ${errors.startDate ? 'border-red-500' : 'border-gray-300'}`}
                    />

                    <CalendarDaysIcon
                      className="absolute right-3 top-[38px] h-5 w-5 text-gray-400 cursor-pointer"
                      onClick={(e) => {
                        const input = e.currentTarget.parentElement?.querySelector(
                          "input"
                        ) as HTMLInputElement;
                        input?.showPicker?.();
                        input?.focus();
                      }}
                    />
                    {errors.startDate && <p className="text-red-500 text-xs mt-1">{errors.startDate.message}</p>}
                  </div>

                  <div className="relative col-span-2 lg:col-span-1">
                    <label className="mb-1.5 block text-sm font-medium text-gray-700">
                      Due Date
                    </label>

                    <input
                      type="date"
                      min={formStartDate || ""}
                      {...register("dueDate", { required: "Due date is required" })}
                      onClick={(e) => e.currentTarget.showPicker?.()}
                      className={`h-11 w-full rounded-lg border appearance-none px-4 py-2.5 pr-10 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-[38px] h-5 w-5 text-gray-400 cursor-pointer"
                      onClick={(e) => {
                        const input = e.currentTarget.parentElement?.querySelector(
                          "input"
                        ) as HTMLInputElement;
                        input?.showPicker?.();
                        input?.focus();
                      }}
                    />
                    {errors.dueDate && <p className="text-red-500 text-xs mt-1">{errors.dueDate.message}</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("trackProgress", {
                        required: "Progress is required",
                        min: { value: 0, message: "Minimum is 0" },
                        max: { value: 100, message: "Maximum is 100" }
                      })}
                      className={`h-11 w-full rounded-lg border px-4 py-2.5 text-sm shadow-theme-xs placeholder:text-gray-400 bg-transparent text-gray-800 outline-none ${errors.trackProgress ? 'border-red-500' : 'border-gray-300'}`}
                    />
                    {errors.trackProgress && <p className="text-red-500 text-xs mt-1">{errors.trackProgress.message}</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", { required: "Status 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.status ? 'border-red-500' : 'border-gray-300'}`}
                      >
                        <option value="Pending">Pending</option>
                        <option value="Active">Active</option>
                        <option value="Hold">Hold</option>
                        <option value="Completed">Completed</option>
                        <option value="Delayed">Delayed</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.status && <p className="text-red-500 text-xs mt-1">{errors.status.message}</p>}
                  </div>

                  <div className="col-span-1 lg:col-span-2">
                    <label className="mb-1.5 block text-sm font-medium text-gray-700">Assign Team Members &nbsp; <span className="text-danger-500">*</span></label>
                    <MultiSelect
                      options={(usersByRole.teamMembers || []).filter((m: any) => m.status?.toUpperCase() === 'ACTIVE' || m.isActive).map((member: any) => ({
                        value: member.id, label: `${member.name} (Team Member)`
                      }))}
                      value={formAssignedTeam}
                      onChange={(newTeam) => { setValue("assignedTeam", newTeam); clearErrors("assignedTeam"); }}
                      placeholder={teamLoading ? "Loading team members..." : "Select team members..."}
                      disabled={teamLoading && (!usersByRole.teamMembers || usersByRole.teamMembers.length === 0)}
                    />
                    {errors.assignedTeam && <p className="text-red-500 text-xs mt-1">{errors.assignedTeam.message as string}</p>}
                  </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"
                    disabled={isSubmitting}
                    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"
                  >
                    {isSubmitting ? (
                      <span className="flex items-center gap-2">
                        <svg className="animate-spin h-4 w-4 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                          <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                          <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                        </svg>
                        {formId ? "Saving..." : "Creating..."}
                      </span>
                    ) : (
                      formId ? "Save Changes" : "Create Milestone"
                    )}
                  </button>
                </div>
              </form>
            </div>
          </Modal>

          {/* Delete Milestone 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">{milestoneToDelete?.name}</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>

          {/* View Milestone Modal */}
          {selectedMilestone && (
            <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">
                    {selectedMilestone.title || selectedMilestone.name}
                  </h4>
                  {/* <p className="mb-6 text-sm text-gray-500 lg:mb-7">
                    ID: {selectedMilestone.id} | Project: {selectedMilestone.project?.title || selectedMilestone.projectId}
                  </p> */}
                </div>

                <div className="px-2 space-y-6 lg:space-y-5">
                  <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
                    <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">Status</p>
                      <p className={`font-medium ${selectedMilestone.status === "Active" ? "text-[#22C55E]" :
                        selectedMilestone.status === "Completed" ? "text-[#2563EB]" :
                          selectedMilestone.status === "Delayed" ? "text-[#EF4444]" :
                            selectedMilestone.status === "Hold" ? "text-orange-600" :
                              "text-gray-600"
                        }`}>
                        {selectedMilestone.status}
                      </p>
                    </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">Team Size</p>
                      <p className="font-medium text-gray-800">
                        {(selectedMilestone.responsibleUsers && selectedMilestone.responsibleUsers.length > 0)
                          ? selectedMilestone.responsibleUsers.length + " Members"
                          : (selectedMilestone.assignedTeam && selectedMilestone.assignedTeam.length > 0)
                            ? selectedMilestone.assignedTeam.length + " Members"
                            : "Unassigned"}
                      </p>
                    </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">Progress</p>
                      <div className="flex items-center gap-2 mt-1">
                        <div className="w-full bg-gray-200 rounded-full h-2.5 max-w-[100px]">
                          <div
                            className="bg-green-600 h-2.5 rounded-full"
                            style={{ width: `${selectedMilestone.trackProgress || 0}%` }}
                          ></div>
                        </div>
                        <span className="text-sm font-medium text-gray-800">{selectedMilestone.trackProgress || 0}%</span>
                      </div>
                    </div>
                  </div>

                  {/* Assigned Members List */}
                  <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">Assigned Team Members</p>
                    <div className="flex flex-wrap gap-2 mt-2">
                      {selectedMilestone?.responsibleUsers && selectedMilestone.responsibleUsers.length > 0 ? (
                        selectedMilestone.responsibleUsers.map((ru: any, idx: number) => (
                          <span key={idx} className="px-3 py-1 bg-white border border-gray-200 rounded-full text-sm font-medium text-gray-700">
                            {[ru?.user?.firstName, ru?.user?.lastName].filter(Boolean).join(' ')}
                          </span>
                        ))
                      ) : selectedMilestone?.assignedTeam && selectedMilestone.assignedTeam.length > 0 ? (
                        selectedMilestone.assignedTeam.map((userId: string, idx: number) => {
                          const user = team.find((u: any) => u.id === userId);
                          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">No members assigned</span>
                      )}
                    </div>
                  </div>

                  <div>
                    <h5 className="mb-4 text-lg font-medium text-gray-800">Milestone 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="mb-1.5 block text-sm font-normal text-gray-500">Description</p>
                          <p className="text-sm font-medium text-gray-800 mt-1 break-all whitespace-pre-wrap">{selectedMilestone.description || "No description provided."}</p>
                        </div>
                      </div>
                      {(selectedMilestone as any).notes && (
                        <div className="pt-4 border-t border-gray-100 flex items-center gap-3 w-full">
                          <div className="min-w-0 w-full">
                            <p className="mb-1.5 block text-sm font-normal text-gray-500">Notes</p>
                            <p className="text-sm font-medium text-gray-800 mt-1 break-all whitespace-pre-wrap">{(selectedMilestone as any).notes}</p>
                          </div>
                        </div>
                      )}
                      <div className="grid grid-cols-2 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">{selectedMilestone.startDate}</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">{selectedMilestone.dueDate}</p>
                        </div>
                      </div>
                    </div>
                  </div>

                </div>


              </div>
            </Modal>
          )}

          {/* Archive Milestone 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">Confirm Archive</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">{milestoneToArchive?.name}</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 Milestone 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">Confirm Un-Archive</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">{milestoneToUndoArchive?.name}</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>
    </>
  );
}
