"use client";
import React, { useState, useEffect } from "react";
import { Eye, Trash2, Pencil, Search, Archive, Undo2 } from "lucide-react";
import { Project } from "@/types";
import { CalendarDaysIcon } from "@heroicons/react/24/outline";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { createProjectApi, updateProjectApi, deleteProjectApi, fetchProjects, getProjectById, clearSelectedProject, archiveProjectApi } from "@/store/slices/projectSlice";
import { fetchTeam } from "@/store/slices/teamSlice";
import { fetchClients } from "@/store/slices/clientSlice";
import { fetchSymbols } from "@/store/slices/symbolSlice";
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 { toast } from "react-toastify";
import axiosInstance from "@/lib/axios";

export default function ProjectsManagementPage() {
  const dispatch = useAppDispatch();
  const { projects, selectedProject, isLoading, error, total } = useAppSelector((state) => state.projects);
  const team = useAppSelector((state) => state.team.members);
  const { clients } = useAppSelector((state) => state.clients);
  const { symbols } = useAppSelector((state) => state.symbols);
  const teamLoading = useAppSelector((state) => state.team.isLoading);
  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('project.view');
  const canEdit = isAdmin || hasPermission('project.update');
  const canDelete = isAdmin || hasPermission('project.delete');
  const canCreate = isAdmin || hasPermission('project.create');
  const canArchive = isAdmin || hasPermission('project.update');

  const today = new Date().toISOString().split("T")[0];

  const { isOpen, openModal, closeModal } = useModal();

  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
  const [projectToDelete, setProjectToDelete] = useState<Project | null>(null);

  const [isArchiveModalOpen, setIsArchiveModalOpen] = useState(false);
  const [projectToArchive, setProjectToArchive] = useState<Project | null>(null);

  const [isUndoArchiveModalOpen, setIsUndoArchiveModalOpen] = useState(false);
  const [projectToUndoArchive, setProjectToUndoArchive] = useState<Project | null>(null);

  const [searchText, setSearchText] = useState("");
  const [rowsPerPage, setRowsPerPage] = useState(10);
  const [currentPage, setCurrentPage] = useState(1);
  const [resetPaginationToggle, setResetPaginationToggle] = useState(false);
  const [formData, setFormData] = useState<Partial<Project> & { currency?: string; memberSettings?: Record<string, any>; team?: string[] }>({});
  const [formErrors, setFormErrors] = useState<Record<string, string>>({});

  const [isViewModalOpen, setIsViewModalOpen] = useState(false);
  const [isArchiveView, setIsArchiveView] = useState(false);
  const [usersByRole, setUsersByRole] = useState<any>({ projectManagers: [], teamLeaders: [], teamMembers: [] });

  useEffect(() => {
    const fetchUsersByRole = async () => {
      try {
        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);
      }
    };
    fetchUsersByRole();
  }, []);

  useEffect(() => {
    dispatch(fetchTeam({ page: 1, limit: 100 }));
    dispatch(fetchClients({}));
    dispatch(fetchSymbols({ isActive: true }));
  }, [dispatch]);

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

  useEffect(() => {
    if (error) {
      toast.error(error);
    }
  }, [error]);

  const handleOpenModal = (project?: Project) => {
    if (project) {
      const p = project as any;
      const initMemberSettings: Record<string, any> = {};
      const memberList = p.teamMembers || p.members;
      if (memberList && Array.isArray(memberList)) {
        memberList.forEach((m: any) => {
          const uId = m.user?.id || m.userId || m.id;
          const rateData = m.user?.developerRates?.[0] || m;

          if (uId) {
            initMemberSettings[uId] = {
              effectiveFrom: rateData.effectiveFrom ? new Date(rateData.effectiveFrom).toISOString().split('T')[0] : "",
              effectiveTo: rateData.effectiveTo ? new Date(rateData.effectiveTo).toISOString().split('T')[0] : "",
              costPerHour: rateData.costPerHour || "",
              billingRate: rateData.billingRatePerHour || rateData.billingRate || "",
              currency: rateData.currency || "₹"
            };
          }
        });
      }

      setFormData({
        ...project,
        name: p.title || p.name || "",
        clientId: p.client?.id || p.clientId || "",
        status: p.status || "ACTIVE",
        startDate: p.startDate ? new Date(p.startDate).toISOString().split('T')[0] : "",
        endDate: p.endDate ? new Date(p.endDate).toISOString().split('T')[0] : "",
        techStack: p.technologyStack || p.techStack || [],
        team: (memberList?.map((m: any) => m.user?.id || m.userId || m.id) || p.team || []).filter(Boolean),
        memberSettings: initMemberSettings,
        projectManagerId: p.projectManager?.id || p.projectManagerId || "",
        teamLeaderId: p.teamLeader?.id || p.teamLeaderId || "",
        notes: p.notes || ""
      });
    } else {
      setFormData({
        name: "",
        description: "",
        clientId: "",
        startDate: "",
        endDate: "",
        budget: "",
        currency: "₹",
        status: "ACTIVE",
        techStack: [],
        team: [],
        gitRepositoryUrl: "",
        stagingUrl: "",
        productionUrl: "",
        apiDocumentationUrl: "",
        notes: "",
        projectManagerId: "",
        teamLeaderId: ""
      });
    }
    setFormErrors({});
    openModal();
  };

  const handleCloseModal = () => {
    setFormData({});
    setFormErrors({});
    closeModal();
  };

  const handleSaveProject = async (e: React.FormEvent) => {
    e.preventDefault();

    const errors: Record<string, string> = {};
    if (!formData.name?.trim()) errors.name = "Project Name is required";
    if (!formData.description?.trim()) errors.description = "Description is required";
    if (!formData.clientId) errors.clientId = "Client is required";
    if (!formData.startDate?.trim()) errors.startDate = "Start Date is required";
    if (!formData.endDate?.trim()) errors.endDate = "End Date is required";

    if (formData.startDate && formData.endDate && new Date(formData.endDate) < new Date(formData.startDate)) {
      errors.endDate = "End Date cannot be before Start Date";
    }
    if (!formData.team || formData.team.length === 0) {
      errors.team = "At least one team member must be assigned";
    }

    if (Object.keys(errors).length > 0) {
      setFormErrors(errors);
      return;
    }

    setFormErrors({});

    const apiPayload: any = {
      ...formData,
      projectName: formData.name,
      teamMembers: (formData.team || []).map((userId: string) => {
        const settings = (formData as any).memberSettings?.[userId] || {};
        return {
          userId,
          effectiveFrom: settings.effectiveFrom || undefined,
          effectiveTo: settings.effectiveTo || undefined,
          costPerHour: settings.costPerHour ? Number(settings.costPerHour) : undefined,
          billingRatePerHour: settings.billingRate ? Number(settings.billingRate) : undefined,
          currency: settings.currency || "₹"
        };
      }),
      budget: formData.budget ? Number(formData.budget) : 0,
      currency: formData.currency || "₹",
      startDate: formData.startDate || undefined,
      endDate: formData.endDate || undefined,
    };




    try {
      if (formData.id) {
        const resultAction = await dispatch(updateProjectApi({ id: formData.id, data: apiPayload }));
        if (updateProjectApi.fulfilled.match(resultAction)) {
          toast.success('Project updated successfully');
          handleCloseModal();
        } else {
          const payload = resultAction.payload as any;
          if (payload && payload.errors && Array.isArray(payload.errors)) {
            const apiErrors: Record<string, string> = {};
            payload.errors.forEach((e: any) => {
              apiErrors[e.field] = e.message;
            });
            setFormErrors(apiErrors);
            toast.error(payload.errors[0]?.message || payload.message || 'Validation failed');
          } else {
            toast.error(typeof payload === 'string' ? payload : (payload?.message || 'Failed to update project'));
          }
        }
      } else {
        const resultAction = await dispatch(createProjectApi(apiPayload));
        if (createProjectApi.fulfilled.match(resultAction)) {
          toast.success('Project created successfully');
          handleCloseModal();
        } else {
          const payload = resultAction.payload as any;
          if (payload && payload.errors && Array.isArray(payload.errors)) {
            const apiErrors: Record<string, string> = {};
            payload.errors.forEach((e: any) => {
              apiErrors[e.field] = e.message;
            });
            setFormErrors(apiErrors);
            toast.error(payload.errors[0]?.message || payload.message || 'Validation failed');
          } else {
            toast.error(typeof payload === 'string' ? payload : (payload?.message || 'Failed to create project'));
          }
        }
      }
    } catch (err: any) {
      toast.error(err.message || 'An error occurred');
    }
  };

  const handleDeleteProject = (project: Project) => {
    setProjectToDelete(project);
    setIsDeleteModalOpen(true);
  };
  const closeDeleteModal = () => {
    setIsDeleteModalOpen(false);
    setProjectToDelete(null);
  };

  const handleViewProject = async (project: Project) => {
    const resultAction = await dispatch(getProjectById(project.id));

    if (getProjectById.fulfilled.match(resultAction)) {
      setIsViewModalOpen(true);
    } else {
      toast.error((resultAction.payload as string) || "Failed to load project details");
    }
  };

  const handleEditProject = async (project: Project) => {
    const resultAction = await dispatch(getProjectById(project.id));
    if (getProjectById.fulfilled.match(resultAction)) {
      handleOpenModal(resultAction.payload as Project);
    } else {
      toast.error((resultAction.payload as string) || "Failed to load project details for editing");
    }
  };

  const closeViewModal = () => {
    setIsViewModalOpen(false);
    dispatch(clearSelectedProject());
  };
  const confirmDelete = async () => {
    if (!projectToDelete) return;

    const resultAction = await dispatch(deleteProjectApi(projectToDelete.id));
    if (deleteProjectApi.fulfilled.match(resultAction)) {
      toast.success(resultAction.payload.message);
      closeDeleteModal();
    } else {
      toast.error((resultAction.payload as string) || 'Failed to delete project');
    }
  };

  const handleUndoArchive = (project: Project) => {
    setProjectToUndoArchive(project);
    setIsUndoArchiveModalOpen(true);
  };

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

  const confirmUndoArchive = async () => {
    if (!projectToUndoArchive) return;

    const resultAction = await dispatch(archiveProjectApi(projectToUndoArchive.id));
    if (archiveProjectApi.fulfilled.match(resultAction)) {
      toast.success("Project un-archived successfully");
      closeUndoArchiveModal();
    } else {
      toast.error((resultAction.payload as string) || "Failed to un-archive project");
    }
  };
  const handleArchiveProject = (project: Project) => {
    setProjectToArchive(project);
    setIsArchiveModalOpen(true);
  };

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

  const confirmArchive = async () => {
    if (!projectToArchive) return;

    const resultAction = await dispatch(archiveProjectApi(projectToArchive.id));
    if (archiveProjectApi.fulfilled.match(resultAction)) {
      toast.success(resultAction.payload.message);
      closeArchiveModal();
    } else {
      toast.error((resultAction.payload as string) || 'Failed to archive project');
    }
  };


  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 "DELAYED": return "bg-[#EF4444]/10 text-[#EF4444]";
      case "CANCELLED": return "bg-[#DC2626]/10 text-[#DC2626]";
      case "DRAFT": return "bg-[#9CA3AF]/10 text-[#9CA3AF]";
      default: return "bg-slate-100 text-slate-600";
    }
  };

  const getTeamMemberName = (id?: string) => {
    if (!id) return "N/A";
    const member = team.find((m: any) => m.id === id);
    if (member) {
      const roleName = (member.role as any)?.name || member.role || "Member";
      return `${member.name} (${roleName})`;
    }
    return id;
  };

  const columns = [
    {
      name: "S.No.",
      sortable: false,
      cell: (row: Project, index: number) => (
        <div data-th="S.No." className="mobile-cell">
          <span className="text-gray-500">{(currentPage - 1) * rowsPerPage + index + 1}</span>
        </div>
      ),
    },
    {
      name: 'Project Name',
      selector: (row: Project) => row.name,
      sortable: true,
      minWidth: "180px",
      cell: (row: Project) => <div data-th="Project Name" className="mobile-cell"><span className="md:font-medium text-gray-600 md:text-gray-900">{row.name}</span></div>
    },
    {
      name: 'Client',
      selector: (row: Project) => row.client,
      sortable: true,
      minWidth: "140px",
      cell: (row: Project) => <div data-th="Client" className="mobile-cell"><span className="text-gray-600">{row.client}</span></div>
    },
    {
      name: 'Start Date',
      selector: (row: Project) => row.startDate,
      sortable: true,
      minWidth: "140px",
      cell: (row: Project) => <div data-th="Start Date" className="mobile-cell"><span className="text-gray-600">{row.startDate}</span></div>
    },
    {
      name: 'End Date',
      selector: (row: Project) => row.endDate,
      sortable: true,
      minWidth: "140px",
      cell: (row: Project) => <div data-th="End Date" className="mobile-cell"><span className="text-gray-600">{row.endDate}</span></div>
    },
    {
      name: 'Budget',
      selector: (row: any) => row.budget ? `${row.currency || ''} ${row.budget}`.trim() : "N/A",
      sortable: true,
      minWidth: "140px",
      cell: (row: any) => <div data-th="Budget" className="mobile-cell"><span className="text-gray-600">{row.budget ? `${row.currency || ''} ${row.budget}`.trim() : "N/A"}</span></div>
    },
    {
      name: 'Status',
      selector: (row: Project) => row.status,
      sortable: true,
      minWidth: "140px",
      cell: (row: Project) => (
        <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: Project) => (
        <div data-th="Action" className="mobile-cell w-full sm:w-auto">
          <div className="flex justify-start sm:justify-center gap-2">
            {isArchiveView ? (
              <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={() => handleUndoArchive(row)}
                title="Undo Archive"
              >
                <Undo2 size={16} />
              </button>
            ) : (
              <>
                {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={() => handleViewProject(row)}
                    title="View Project"
                  >
                    <Eye size={16} />
                  </button>
                )}

                {canEdit && (
                  <button
                    className="w-8 h-8 rounded-md bg-amber-500/10 flex items-center justify-center text-amber-600 hover:bg-amber-500/20 transition-colors"
                    onClick={() => handleEditProject(row)}
                    title="Edit Project"
                  >
                    <Pencil size={16} />
                  </button>
                )}

                {canArchive && (
                  <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={() => handleArchiveProject(row)}
                    title="Archive Project"
                  >
                    <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={() => handleDeleteProject(row)}
                    title="Delete Project"
                  >
                    <Trash2 size={16} />
                  </button>
                )}
              </>
            )}
          </div>
        </div>
      )
    } as any);
  }

  const filteredProjects = projects.filter(
    (project: any) =>
      project.name?.toLowerCase().includes(searchText.toLowerCase()) ||
      project.client?.toLowerCase().includes(searchText.toLowerCase()) ||
      project.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">Project Management</h1>
              <p className="text-sm text-gray-500 mt-1">Manage company projects 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 Project</span>
            </button>
          )}
        </div>

        {/* Projects 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-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 projects..."
                    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={filteredProjects}
                progressPending={isLoading}
                pagination
                paginationResetDefaultPage={resetPaginationToggle}
                paginationServer
                paginationTotalRows={total}
                paginationPerPage={rowsPerPage}
                onChangePage={(page) => setCurrentPage(page)}
                onChangeRowsPerPage={(newPerPage) => {
                  setRowsPerPage(newPerPage);
                  setCurrentPage(1);
                }}
                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">
                {formData.id ? "Edit Project" : "Create New Project"}
              </h4>
            </div>
            <form onSubmit={handleSaveProject} 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">Project Name</label>
                  <input
                    type="text"
                    value={formData.name || ""}
                    onChange={(e) => {
                      setFormData({ ...formData, name: e.target.value });
                      if (formErrors.name) setFormErrors({ ...formErrors, name: "" });
                    }}
                    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 ${formErrors.name ? 'border-red-500' : 'border-gray-300'}`}
                    placeholder="E.g. Hotel Management System"
                  />
                  {formErrors.name && <p className="mt-1.5 text-xs text-red-500">{formErrors.name}</p>}
                </div>

                <div className="col-span-2">
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Description</label>
                  <textarea
                    value={formData.description || ""}
                    onChange={(e) => {
                      setFormData({ ...formData, description: e.target.value });
                      if (formErrors.description) setFormErrors({ ...formErrors, description: "" });
                    }}
                    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] ${formErrors.description ? 'border-red-500' : 'border-gray-300'}`}
                    placeholder="Detailed project description..."
                  />
                  {formErrors.description && <p className="mt-1.5 text-xs text-red-500">{formErrors.description}</p>}
                </div>

                <div className="col-span-2 lg:col-span-1">
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Client</label>
                  <div className="relative">
                    <select
                      value={formData.clientId || ""}
                      onChange={(e) => {
                        setFormData({ ...formData, clientId: e.target.value });
                        if (formErrors.clientId) setFormErrors({ ...formErrors, clientId: "" });
                      }}
                      className={`h-11 w-full rounded-lg border appearance-none px-4 py-2.5 text-sm shadow-theme-xs bg-transparent text-gray-800 outline-none ${formErrors.clientId ? 'border-red-500' : 'border-gray-300'}`}
                    >
                      <option value="" disabled>Select a client</option>
                      {clients.filter(client => client.isActive !== false).map(client => (
                        <option key={client.id} value={client.id}>{client.name}</option>
                      ))}
                    </select>
                    <span className="absolute text-gray-500 -translate-y-1/2 pointer-events-none right-3 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>
                  {formErrors.clientId && <p className="mt-1.5 text-xs text-red-500">{formErrors.clientId}</p>}
                </div>

                <div className="col-span-2 lg:col-span-1">
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Budget (Optional)</label>
                  <div className="flex h-11 rounded-lg border border-gray-300 shadow-theme-xs bg-transparent">
                    <select
                      value={formData.currency || "₹"}
                      onChange={(e) => setFormData({ ...formData, currency: e.target.value })}
                      className="h-full rounded-l-lg border-r border-transparent bg-gray-50 px-3 text-sm text-gray-700 outline-none hover:bg-gray-100"
                    >
                      {symbols && symbols.length > 0 ? (
                        symbols.map(s => (
                          <option key={s.id} value={s.code}>{s.code}</option>
                        ))
                      ) : (
                        <>
                          <option value="₹">₹</option>
                          <option value="$">$</option>
                          <option value="€">€</option>
                          <option value="£">£</option>
                          <option value="¥">¥</option>
                        </>
                      )}
                    </select>
                    <input
                      type="number"
                      min="0"
                      step="0.01"
                      inputMode="decimal"
                      value={formData.budget || ""}
                      onChange={(e) => setFormData({ ...formData, budget: e.target.value })}
                      className="h-full w-full rounded-r-lg border-none px-4 py-2.5 text-sm placeholder:text-gray-400 text-gray-800 outline-none"
                      placeholder="E.g. 5000"
                    />
                  </div>
                </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"
                    value={formData.startDate || ""}
                    onClick={(e) => e.currentTarget.showPicker?.()}
                    onChange={(e) => {
                      setFormData({
                        ...formData,
                        startDate: e.target.value,
                      });
                      if (formErrors.startDate) setFormErrors({ ...formErrors, startDate: "" });
                    }}
                    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 ${formErrors.startDate ? 'border-red-500' : 'border-gray-300'}`}
                  />
                  {formErrors.startDate && <p className="mt-1.5 text-xs text-red-500">{formErrors.startDate}</p>}

                  <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();
                    }}
                  />
                </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>
                  <input
                    type="date"
                    min={formData.startDate || ""}
                    value={formData.endDate || ""}
                    onClick={(e) => e.currentTarget.showPicker?.()}
                    onChange={(e) => {
                      setFormData({
                        ...formData,
                        endDate: e.target.value,
                      });
                      if (formErrors.endDate) setFormErrors({ ...formErrors, endDate: "" });
                    }}
                    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 ${formErrors.endDate ? 'border-red-500' : 'border-gray-300'}`}
                  />
                  {formErrors.endDate && <p className="mt-1.5 text-xs text-red-500">{formErrors.endDate}</p>}

                  <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();
                    }}
                  />
                </div>

                <div className="col-span-2 lg:col-span-1">
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Tech Stack (comma separated)</label>
                  <input
                    type="text"
                    value={formData.techStack?.join(", ") || ""}
                    onChange={(e) => setFormData({ ...formData, techStack: e.target.value.split(",").map(s => s.trim()) })}
                    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"
                    placeholder="React, Node, MongoDB"
                  />
                </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
                      value={formData.status || "ACTIVE"}
                      onChange={(e) => setFormData({ ...formData, status: e.target.value as Project["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="DRAFT">Draft</option>
                      <option value="ACTIVE">Active</option>
                      <option value="ON_HOLD">On Hold</option>
                      <option value="COMPLETED">Completed</option>
                      <option value="CANCELLED">Cancelled</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">
                      <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>
                  {formErrors.status && <p className="mt-1.5 text-xs text-red-500">{formErrors.status}</p>}
                </div>

                <div className="col-span-2">
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Git Repository URL (Optional)</label>
                  <input
                    type="url"
                    value={formData.gitRepositoryUrl || ""}
                    onChange={(e) => setFormData({ ...formData, gitRepositoryUrl: e.target.value })}
                    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"
                    placeholder="https://github.com/..."
                  />
                </div>

                <div className="col-span-2 lg:col-span-1">
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Staging URL (Optional)</label>
                  <input
                    type="url"
                    value={formData.stagingUrl || ""}
                    onChange={(e) => setFormData({ ...formData, stagingUrl: e.target.value })}
                    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"
                    placeholder="https://staging.company.com"
                  />
                </div>

                <div className="col-span-2 lg:col-span-1">
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Production URL (Optional)</label>
                  <input
                    type="url"
                    value={formData.productionUrl || ""}
                    onChange={(e) => setFormData({ ...formData, productionUrl: e.target.value })}
                    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"
                    placeholder="https://company.com"
                  />
                </div>

                <div className="col-span-2">
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">API Documentation URL (Optional)</label>
                  <input
                    type="url"
                    value={formData.apiDocumentationUrl || ""}
                    onChange={(e) => setFormData({ ...formData, apiDocumentationUrl: e.target.value })}
                    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"
                    placeholder="https://company.com/swagger"
                  />
                </div>

                <div className="col-span-2">
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Notes</label>
                  <textarea
                    value={formData.notes || ""}
                    onChange={(e) => setFormData({ ...formData, notes: e.target.value })}
                    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] border-gray-300"
                    placeholder="Additional notes..."
                  />
                  {formErrors.notes && <p className="mt-1.5 text-xs text-red-500">{formErrors.notes}</p>}
                </div>

                <div className="col-span-2 lg:col-span-1">
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Project Manager</label>
                  <div className="relative">
                    <select
                      value={formData.projectManagerId || ""}
                      onChange={(e) => setFormData({ ...formData, projectManagerId: e.target.value })}
                      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 Project Manager</option>
                      {(usersByRole.projectManagers || [])
                        .filter((member: any) => member.status === 'ACTIVE')
                        .map((member: any) => (
                        <option key={`pm-${member.id}`} value={member.id}>
                          {member.name} (Project Manager)
                        </option>
                      ))}
                    </select>
                    <span className="absolute text-gray-500 -translate-y-1/2 pointer-events-none right-3 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>
                </div>

                <div className="col-span-2 lg:col-span-1">
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Team Leader</label>
                  <div className="relative">
                    <select
                      value={formData.teamLeaderId || ""}
                      onChange={(e) => setFormData({ ...formData, teamLeaderId: e.target.value })}
                      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 Team Leader</option>
                      {(usersByRole.teamLeaders || [])
                        .filter((member: any) => member.status === 'ACTIVE')
                        .map((member: any) => (
                        <option key={`tl-${member.id}`} value={member.id}>
                          {member.name} (Team Leader)
                        </option>
                      ))}
                    </select>
                    <span className="absolute text-gray-500 -translate-y-1/2 pointer-events-none right-3 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>
                  {formErrors.teamLeaderId && <p className="mt-1.5 text-xs text-red-500">{formErrors.teamLeaderId}</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</label>
                  <MultiSelect
                    options={(usersByRole.teamMembers || [])
                      .filter((member: any) => member.status === 'ACTIVE')
                      .map((member: any) => ({
                      value: member.id, label: `${member.name} (Team Member)`
                    }))}
                    value={formData.team || []}
                    onChange={(newTeam) => setFormData({ ...formData, team: newTeam })}
                    placeholder={teamLoading ? "Loading team members..." : "Select team members..."}
                    disabled={teamLoading && team.length === 0}
                  />
                  {formErrors.team && <p className="text-red-500 text-xs mt-1">{formErrors.team}</p>}
                  {!teamLoading && team.length === 0 && (
                    <span className="text-sm text-gray-500 mt-2 block">No team members available. Add some in Team Management first.</span>
                  )}

                  {formData.team && formData.team.length > 0 && (
                    <div className="mt-6 space-y-6">
                      {formData.team.map((userId: string) => {
                        const memberInfo = (usersByRole.teamMembers || []).find((m: any) => m.id === userId);
                        const memberName = memberInfo ? memberInfo.name : "Member";
                        const settings = (formData as any).memberSettings?.[userId] || {};

                        const updateMemberSetting = (field: string, value: any) => {
                          const currentSettings = (formData as any).memberSettings || {};
                          setFormData({
                            ...formData,
                            memberSettings: {
                              ...currentSettings,
                              [userId]: {
                                ...(currentSettings[userId] || {}),
                                [field]: value
                              }
                            }
                          } as any);
                        };

                        return (
                          <div key={userId} className="p-4 border border-gray-200 rounded-xl bg-gray-50 space-y-4">
                            <h5 className="font-semibold text-brand-950 text-sm border-b pb-2 mb-3">Settings for {memberName}</h5>
                            <div className="grid grid-cols-1 gap-x-6 gap-y-4 lg:grid-cols-2">
                              <div>
                                <label className="mb-1.5 block text-sm font-medium text-gray-700">Cost Per Hour (Optional)</label>
                                <input
                                  type="number"
                                  value={settings.costPerHour || ""}
                                  onChange={(e) => updateMemberSetting("costPerHour", e.target.value)}
                                  className="h-11 w-full rounded-lg border border-gray-300 appearance-none px-4 py-2.5 text-sm shadow-theme-xs bg-white text-gray-800 outline-none"
                                />
                              </div>
                              <div>
                                <label className="mb-1.5 block text-sm font-medium text-gray-700">Billing Rate Per Hour (Optional)</label>
                                <input
                                  type="number"
                                  value={settings.billingRate || ""}
                                  onChange={(e) => updateMemberSetting("billingRate", e.target.value)}
                                  className="h-11 w-full rounded-lg border border-gray-300 appearance-none px-4 py-2.5 text-sm shadow-theme-xs bg-white text-gray-800 outline-none"
                                />
                              </div>
                              <div className="lg:col-span-2">
                                <label className="mb-1.5 block text-sm font-medium text-gray-700">Currency (Optional)</label>
                                <select
                                  value={settings.currency || "₹"}
                                  onChange={(e) => updateMemberSetting("currency", e.target.value)}
                                  className="h-11 w-full lg:w-1/2 rounded-lg border border-gray-300 appearance-none px-4 py-2.5 text-sm shadow-theme-xs bg-white text-gray-800 outline-none"
                                >
                                  {symbols && symbols.length > 0 ? (
                                    symbols.map((s: any) => (
                                      <option key={s.id} value={s.code}>{s.code}</option>
                                    ))
                                  ) : (
                                    <>
                                      <option value="₹">₹</option>
                                      <option value="$">$</option>
                                      <option value="€">€</option>
                                      <option value="£">£</option>
                                      <option value="¥">¥</option>
                                    </>
                                  )}
                                </select>
                              </div>
                              <div className="relative">
                                <label className="mb-1.5 block text-sm font-medium text-gray-700">Effective From <span className="text-red-500">*</span></label>
                                <input
                                  type="date"
                                  value={settings.effectiveFrom || ""}
                                  onClick={(e) => e.currentTarget.showPicker?.()}
                                  onChange={(e) => updateMemberSetting("effectiveFrom", e.target.value)}
                                  className="h-11 w-full rounded-lg border border-gray-300 appearance-none px-4 py-2.5 pr-10 text-sm shadow-theme-xs bg-white text-gray-800 outline-none"
                                  required
                                />
                                <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();
                                  }}
                                />
                              </div>
                              <div className="relative">
                                <label className="mb-1.5 block text-sm font-medium text-gray-700">Effective To <span className="text-red-500">*</span></label>
                                <input
                                  type="date"
                                  value={settings.effectiveTo || ""}
                                  onClick={(e) => e.currentTarget.showPicker?.()}
                                  onChange={(e) => updateMemberSetting("effectiveTo", e.target.value)}
                                  className="h-11 w-full rounded-lg border border-gray-300 appearance-none px-4 py-2.5 pr-10 text-sm shadow-theme-xs bg-white text-gray-800 outline-none"
                                  required
                                />
                                <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();
                                  }}
                                />
                              </div>
                            </div>
                          </div>
                        );
                      })}
                    </div>
                  )}
                </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"
                >
                  {formData.id ? "Save Changes" : "Create Project"}
                </button>
              </div>
            </form>
          </div>
        </Modal>

        {/* Delete Project 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">{projectToDelete?.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>

        {/* Archive Project 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">{projectToArchive?.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 Project 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">{projectToUndoArchive?.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>

        {/* View Project Modal */}
        {selectedProject && (
          <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">
                  {selectedProject.name}
                </h4>

              </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-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 ${selectedProject.status === "ACTIVE" ? "text-[#22C55E]" :
                      selectedProject.status === "COMPLETED" ? "text-[#2563EB]" :
                        "text-[#9CA3AF]"
                      }`}>
                      {selectedProject.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">Client</p>
                    <p className="font-medium text-gray-800">{typeof selectedProject.client === 'string' ? selectedProject.client : selectedProject.client?.name || "N/A"}</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">Budget</p>
                    <p className="font-medium text-gray-800">
                      {selectedProject.currency ? selectedProject.currency + " " : ""}{selectedProject.budget || "N/A"}
                    </p>
                  </div>
                </div>

                {selectedProject.technologyStack && selectedProject.technologyStack.length > 0 && (
                  <div>
                    <h5 className="mb-4 text-lg font-medium text-gray-800">Technology Stack</h5>
                    <div className="bg-white border border-gray-200 rounded-lg p-4 flex flex-wrap gap-2">
                      {selectedProject.technologyStack.map((tech: string, idx: number) => (
                        <span key={idx} className="px-3 py-1 bg-gray-50 border border-gray-200 rounded-full text-sm font-medium text-gray-700">
                          {tech}
                        </span>
                      ))}
                    </div>
                  </div>
                )}

                <div>
                  <h5 className="mb-4 text-lg font-medium text-gray-800">Project 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">{selectedProject.description || "No description provided."}</p>
                      </div>
                    </div>
                    {selectedProject.notes && (
                      <div className="pt-4 border-t border-gray-100">
                        <p className="text-sm text-gray-500 font-normal">Notes</p>
                        <p className="text-sm font-medium text-gray-800 mt-1.5">{selectedProject.notes}</p>
                      </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">{selectedProject.startDate || "N/A"}</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">{selectedProject.endDate || "N/A"}</p>
                      </div>
                    </div>
                  </div>
                </div>

                <div>
                  <h5 className="mb-4 text-lg font-medium text-gray-800">URLs & Links</h5>
                  <div className="bg-white border border-gray-200 rounded-lg p-4 grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div>
                      <p className="mb-1.5 block text-sm font-normal text-gray-500">Git Repository</p>
                      <p className="text-sm font-medium text-gray-800 break-all">
                        {selectedProject.gitRepositoryUrl ? (
                          <a href={selectedProject.gitRepositoryUrl} target="_blank" rel="noopener noreferrer" className="text-blue-600 hover:underline">
                            {selectedProject.gitRepositoryUrl}
                          </a>
                        ) : "N/A"}
                      </p>
                    </div>
                    <div>
                      <p className="mb-1.5 block text-sm font-normal text-gray-500">API Documentation</p>
                      <p className="text-sm font-medium text-gray-800 break-all">
                        {selectedProject.apiDocumentationUrl ? (
                          <a href={selectedProject.apiDocumentationUrl} target="_blank" rel="noopener noreferrer" className="text-blue-600 hover:underline">
                            {selectedProject.apiDocumentationUrl}
                          </a>
                        ) : "N/A"}
                      </p>
                    </div>
                    <div>
                      <p className="mb-1.5 block text-sm font-normal text-gray-500">Staging URL</p>
                      <p className="text-sm font-medium text-gray-800 break-all">
                        {selectedProject.stagingUrl ? (
                          <a href={selectedProject.stagingUrl} target="_blank" rel="noopener noreferrer" className="text-blue-600 hover:underline">
                            {selectedProject.stagingUrl}
                          </a>
                        ) : "N/A"}
                      </p>
                    </div>
                    <div>
                      <p className="mb-1.5 block text-sm font-normal text-gray-500">Production URL</p>
                      <p className="text-sm font-medium text-gray-800 break-all">
                        {selectedProject.productionUrl ? (
                          <a href={selectedProject.productionUrl} target="_blank" rel="noopener noreferrer" className="text-blue-600 hover:underline">
                            {selectedProject.productionUrl}
                          </a>
                        ) : "N/A"}
                      </p>
                    </div>
                  </div>
                </div>

                <div>
                  <h5 className="mb-4 text-lg font-medium text-gray-800">Team Information</h5>
                  <div className="bg-white border border-gray-200 rounded-lg p-4 space-y-4">
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                      <div>
                        <p className="mb-1.5 block text-sm font-normal text-gray-500">Project Manager</p>
                        <p className="text-sm font-medium text-gray-800">{selectedProject.projectManager?.firstName ? `${selectedProject.projectManager.firstName} ${selectedProject.projectManager.lastName || ''}` : getTeamMemberName(selectedProject.projectManagerId)}</p>
                      </div>
                      <div>
                        <p className="mb-1.5 block text-sm font-normal text-gray-500">Team Leader</p>
                        <p className="text-sm font-medium text-gray-800">{selectedProject.teamLeader?.firstName ? `${selectedProject.teamLeader.firstName} ${selectedProject.teamLeader.lastName || ''}` : getTeamMemberName(selectedProject.teamLeaderId)}</p>
                      </div>
                    </div>
                    <div className="pt-4 border-t border-gray-100">
                      <p className="mb-1.5 block text-sm font-normal text-gray-500">Team Members ({selectedProject.members?.length || selectedProject.team?.length || 0})</p>
                      <div className="flex flex-wrap gap-2 mt-2">
                        {selectedProject.members && selectedProject.members.length > 0 ? (
                          selectedProject.members.map((m: any, idx: number) => (
                            <span key={idx} className="px-3 py-1 bg-gray-50 border border-gray-200 rounded-full text-sm font-medium text-gray-700">
                              {[m.user?.firstName, m.user?.lastName].filter(Boolean).join(' ')}
                              {m.roleInProject ? ` (${m.roleInProject})` : ""}
                            </span>
                          ))
                        ) : selectedProject.team && selectedProject.team.length > 0 ? (
                          selectedProject.team.map((userId: string, idx: number) => {
                            const user = team.find((u: any) => u.id === userId);
                            return (
                              <span key={idx} className="px-3 py-1 bg-gray-50 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 team members assigned</span>
                        )}
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              {/* <div className="flex items-center gap-3 px-2 mt-6 lg:justify-end">
                <button
                  onClick={closeViewModal}
                  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"
                >
                  Close
                </button>
                <button
                  onClick={() => {
                    closeViewModal();
                    handleOpenModal(selectedProject);
                  }}
                  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"
                >
                  Edit Project
                </button>
              </div> */}
            </div>
          </Modal>
        )}
      </div>
    </div>
  );
}
