"use client";
import React, { useState, useEffect } from "react";
import { Eye, Trash2, ChevronDown, ChevronLeft, ChevronRight, X, Pencil, Plus, Search, Archive, Undo2 } from "lucide-react";
import { Sprint, Milestone } from "@/types";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { CalendarDaysIcon } from "@heroicons/react/24/outline";
import { fetchSprints, createSprint, updateSprint, deleteSprint, toggleArchiveSprint } from "@/store/slices/sprintSlice";
import { fetchMilestones } from "@/store/slices/milestoneSlice";
import DataTable from "react-data-table-component";
import { useModal } from "@/hooks/useModal";
import { Modal } from "@/components/common/modal";
import { useForm } from "react-hook-form";
import { toast } from "react-toastify";

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

  const { isOpen, openModal, closeModal } = useModal();
  const { register, handleSubmit, reset, watch, formState: { errors } } = useForm<Partial<Sprint>>({
    defaultValues: { status: "Planning", progress: 0 }
  });
  const sprintId = watch("id");
  const sprintStartDate = watch("startDate");

  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
  const [sprintToDelete, setSprintToDelete] = useState<Sprint | null>(null);

  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 [sprintToArchive, setSprintToArchive] = useState<Sprint | null>(null);
  const [isUndoArchiveModalOpen, setIsUndoArchiveModalOpen] = useState(false);
  const [sprintToUndoArchive, setSprintToUndoArchive] = useState<Sprint | null>(null);

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

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

  const [isViewModalOpen, setIsViewModalOpen] = useState(false);
  const [selectedSprint, setSelectedSprint] = useState<Sprint | null>(null);

  const handleOpenModal = (sprint?: Sprint) => {
    if (sprint) {
      reset(sprint);
    } else {
      reset({
        id: undefined,
        name: "",
        goal: "",
        milestoneId: "",
        startDate: "",
        endDate: "",
        status: "Planning",
        progress: 0
      });
    }
    openModal();
  };

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

  const handleSaveSprint = (data: Partial<Sprint>) => {
    const selectedMilestone = milestones.find(m => m.id === data.milestoneId);
    const payload = {
      ...data,
      status: (data.status ? data.status.toUpperCase() : "PLANNING") as any,
      progressPercentage: data.progress,
      projectId: selectedMilestone?.projectId
    };

    if (data.id) {
      dispatch(updateSprint({ id: data.id, data: payload })).then((resultAction: any) => {
        if (updateSprint.fulfilled.match(resultAction)) {
          toast.success("Sprint updated successfully");
          dispatch(fetchSprints({ page: currentPage, limit: rowsPerPage, search: searchText }));
          handleCloseModal();
        } else {
          toast.error(resultAction.payload?.message || resultAction.payload || "Failed to update sprint");
        }
      });
    } else {
      dispatch(createSprint(payload)).then((resultAction: any) => {
        if (createSprint.fulfilled.match(resultAction)) {
          toast.success("Sprint created successfully");
          dispatch(fetchSprints({ page: currentPage, limit: rowsPerPage, search: searchText }));
          handleCloseModal();
        } else {
          toast.error(resultAction.payload?.message || resultAction.payload || "Failed to create sprint");
        }
      });
    }
  };

  const handleDeleteSprint = (sprint: Sprint) => {
    setSprintToDelete(sprint);
    setIsDeleteModalOpen(true);
  };
  const closeDeleteModal = () => {
    setIsDeleteModalOpen(false);
    setSprintToDelete(null);
  };

  const handleViewSprint = (sprint: Sprint) => {
    setSelectedSprint(sprint);
    setIsViewModalOpen(true);
  };

  const closeViewModal = () => {
    setIsViewModalOpen(false);
    setSelectedSprint(null);
  };
  const confirmDelete = () => {
    if (sprintToDelete) {
      dispatch(deleteSprint(sprintToDelete.id)).then((resultAction: any) => {
        if (deleteSprint.fulfilled.match(resultAction)) {
          toast.success("Sprint deleted successfully");
          dispatch(fetchSprints({ page: currentPage, limit: rowsPerPage, search: searchText, archived: isArchiveView }));
        } else {
          toast.error(resultAction.payload?.message || resultAction.payload || "Failed to delete sprint");
        }
      });
    }
    closeDeleteModal();
  };

  const handleArchiveSprint = (sprint: Sprint) => {
    setSprintToArchive(sprint);
    setIsArchiveModalOpen(true);
  };
  const closeArchiveModal = () => {
    setIsArchiveModalOpen(false);
    setSprintToArchive(null);
  };
  const confirmArchive = async () => {
    if (sprintToArchive) {
      try {
        await dispatch(toggleArchiveSprint(sprintToArchive.id!)).unwrap();
        toast.success("Sprint archived successfully");
        closeArchiveModal();
      } catch (error: any) {
        toast.error(error || "Failed to archive sprint");
        closeArchiveModal();
      }
    }
  };

  const handleUndoArchiveSprint = (sprint: Sprint) => {
    setSprintToUndoArchive(sprint);
    setIsUndoArchiveModalOpen(true);
  };
  const closeUndoArchiveModal = () => {
    setIsUndoArchiveModalOpen(false);
    setSprintToUndoArchive(null);
  };
  const confirmUndoArchive = async () => {
    if (sprintToUndoArchive) {
      try {
        await dispatch(toggleArchiveSprint(sprintToUndoArchive.id!)).unwrap();
        toast.success("Sprint un-archived successfully");
        closeUndoArchiveModal();
      } catch (error: any) {
        toast.error(error || "Failed to un-archive sprint");
        closeUndoArchiveModal();
      }
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case "Completed": return "bg-[#2563EB]/10 text-[#2563EB]";
      case "Active": return "bg-[#22C55E]/10 text-[#22C55E]";
      case "On Hold": return "bg-orange-100 text-orange-600";
      case "Planning": return "bg-[#7C3AED]/10 text-[#7C3AED]"
      default: return "bg-slate-100 text-slate-600";
    }
  };

  const columns = [
    {
      name: "S.No.",
      sortable: false,
      cell: (row: Sprint, index: number) => (
        <div data-th="S.No." className="mobile-cell">
          <span className="text-gray-500">{(currentPage - 1) * rowsPerPage + index + 1}</span>
        </div>
      ),
    },
    {
      name: 'Sprint Name',
      selector: (row: Sprint) => row.name,
      sortable: true,
      minWidth: "180px",
      cell: (row: Sprint) => <div data-th="Sprint Name" className="mobile-cell"><span className="md:font-medium text-gray-600 md:text-gray-900">{row.name}</span></div>
    },
    {
      name: 'Milestone',
      selector: (row: Sprint) => row.milestoneId,
      sortable: true,
      minWidth: "120px",
      cell: (row: Sprint) => {
        const milestoneName = row.milestone?.title || milestones.find(m => m.id === row.milestoneId)?.name || row.milestoneId;
        return <div data-th="Milestone" className="mobile-cell"><span className="text-gray-600">{milestoneName}</span></div>;
      }
    },
    {
      name: 'Duration',
      selector: (row: Sprint) => row.startDate,
      sortable: true,
      minWidth: "200px",
      cell: (row: Sprint) => (
        <div data-th="Duration" className="mobile-cell text-gray-600 text-sm">
          <div>{row.startDate} to {row.endDate}</div>
        </div>
      )
    },
    {
      name: 'Goal',
      selector: (row: Sprint) => row.goal,
      sortable: true,
      minWidth: "120px",
      cell: (row: Sprint) => (
        <div data-th="Goal" className="mobile-cell">
          <span className="text-gray-600" title={row.goal}>
            {row.goal}
          </span>
        </div>
      )
    },
    {
      name: 'Progress',
      selector: (row: Sprint) => row.progress,
      sortable: true,
      minWidth: "180px",
      cell: (row: Sprint) => (
        <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.progress}%` }}
            ></div>
          </div>
          <span className="text-sm text-gray-600">{row.progress}%</span>
        </div>
      )
    },
    {
      name: 'Status',
      selector: (row: Sprint) => row.status,
      sortable: true,
      minWidth: "120px",
      cell: (row: Sprint) => (
        <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: Sprint) => (
        <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={() => handleViewSprint(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={() => handleArchiveSprint(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={() => handleDeleteSprint(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={() => handleUndoArchiveSprint(row)}
                  >
                    <Undo2 size={16} />
                  </button>
                )}
              </>
            )}
          </div>
        </div>
      )
    } as any);
  }

  // Local filtering removed because the API already filters based on searchText.

  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">Sprint 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 Sprint</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>

        {/* Sprints 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 sprints..."
                    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={sprints || []}
                pagination
                paginationResetDefaultPage={resetPaginationToggle}
                paginationServer
                paginationTotalRows={total}
                paginationComponentOptions={{ noRowsPerPage: true }}
                onChangePage={(page) => setCurrentPage(page)}
                onChangeRowsPerPage={(newPerPage, page) => {
                  setRowsPerPage(newPerPage);
                  setCurrentPage(page);
                  setResetPaginationToggle(!resetPaginationToggle);
                }}
                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">
                {sprintId ? "Edit Sprint" : "Create New Sprint"}
              </h4>
            </div>

            <form onSubmit={handleSubmit(handleSaveSprint)} className="px-2">
              <div className="grid grid-cols-1 gap-x-6 gap-y-5 lg:grid-cols-2">
                <div className="col-span-2">
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Sprint Name</label>
                  <input
                    type="text"
                    {...register("name", { required: "Sprint 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. Sprint 1"
                  />
                  {errors.name && <p className="text-red-500 text-xs mt-1">{errors.name.message as string}</p>}
                </div>

                <div className="col-span-2">
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Select Milestone</label>
                  <div className="relative">
                    <select
                      {...register("milestoneId", { required: "Milestone 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.milestoneId ? 'border-red-500' : 'border-gray-300'}`}
                    >
                      <option value="" disabled>Select a milestone...</option>
                      {milestones.filter(m => m.status?.toUpperCase() === 'ACTIVE').map(m => (
                        <option key={m.id} value={m.id}>{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>
                  {errors.milestoneId && <p className="text-red-500 text-xs mt-1">{errors.milestoneId.message as string}</p>}
                </div>

                <div className="col-span-2">
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Sprint Goal</label>
                  <textarea
                    {...register("goal", { required: "Sprint Goal 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.goal ? 'border-red-500' : 'border-gray-300'}`}
                    placeholder="What is the main objective of this sprint?"
                  />
                  {errors.goal && <p className="text-red-500 text-xs mt-1">{errors.goal.message as string}</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>

                  <div className="relative">
                    <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-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.startDate && <p className="text-red-500 text-xs mt-1">{errors.startDate.message as string}</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">
                    End Date
                  </label>

                  <div className="relative">
                    <input
                      type="date"
                      min={sprintStartDate || ""}
                      {...register("endDate", { required: "End 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.endDate ? '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.endDate && <p className="text-red-500 text-xs mt-1">{errors.endDate.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", { 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="Planning">Planning</option>
                      <option value="Active">Active</option>
                      <option value="Hold">Hold</option>
                      <option value="Completed">Completed</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 as string}</p>}
                </div>

                <div className="col-span-2 lg:col-span-1">
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Progress (%)</label>
                  <input
                    type="number"
                    {...register("progress", {
                      required: "Progress is required",
                      min: { value: 0, message: "Minimum is 0" },
                      max: { value: 100, message: "Maximum is 100" },
                      valueAsNumber: true
                    })}
                    className={`h-11 w-full rounded-lg border appearance-none px-4 py-2.5 text-sm shadow-theme-xs placeholder:text-gray-400 bg-transparent text-gray-800 outline-none ${errors.progress ? 'border-red-500' : 'border-gray-300'}`}
                  />
                  {errors.progress && <p className="text-red-500 text-xs mt-1">{errors.progress.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"
                  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"
                >
                  {sprintId ? "Save Changes" : "Create Sprint"}
                </button>
              </div>
            </form>
          </div>
        </Modal>

        {/* Delete Sprint 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">{sprintToDelete?.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 Sprint Modal */}
        {selectedSprint && (
          <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">
                  {selectedSprint.name}
                </h4>
                {/* <p className="mb-6 text-sm text-gray-500 lg:mb-7">
                  ID: {selectedSprint.id} | Project: {(selectedSprint as any).project?.title || selectedSprint.projectId || 'N/A'} | Milestone: {(selectedSprint as any).milestone?.title || selectedSprint.milestoneId || '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 ${selectedSprint.status === "Active" ? " text-[#22C55E]" :
                      selectedSprint.status === "Completed" ? "text-[#2563EB]" :
                        selectedSprint.status === "Planning" ? "text-[#7C3AED]" :
                          selectedSprint.status === "Hold" ? "text-orange-600" :
                            "text-gray-600"
                      }`}>
                      {selectedSprint.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">{(selectedSprint 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">Capacity / Vel.</p>
                    <p className="font-medium text-gray-800">{(selectedSprint as any).capacity || 0} / {(selectedSprint as any).velocity || 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: `${selectedSprint.progress || 0}%` }}></div>
                      </div>
                      <span className="text-sm font-medium text-gray-700">{selectedSprint.progress || 0}%</span>
                    </div>
                  </div>
                </div>

                <div>
                  <h5 className="mb-4 text-lg font-medium text-gray-800">Sprint 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">Goal</p>
                        <p className="text-sm font-medium text-gray-800 break-all whitespace-pre-wrap">{selectedSprint.goal || "No goal provided."}</p>
                      </div>
                    </div>
                    {(selectedSprint 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 break-all whitespace-pre-wrap">{(selectedSprint 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">{selectedSprint.startDate}</p>
                      </div>
                      <div>
                        <p className="mb-1.5 block text-sm font-normal text-gray-500">End Date</p>
                        <p className="text-sm font-medium text-gray-800">{selectedSprint.endDate}</p>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </Modal>
        )}

        {/* Archive Sprint 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">{sprintToArchive?.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 Sprint 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">{sprintToUndoArchive?.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>
  );
}
