"use client";
import { useState } from "react";
import { Button } from "ikoncomponents";
import { Plus, Edit } from "lucide-react";
import ScheduleGanttShowComponent from "./schedule_show_gantt_component";
import ScheduleFormComponent from "./schedule_form_component/schedule_form_definition";

interface ScheduleTabProps {
  projectIdentifier: string;
}

function ScheduleTab({ projectIdentifier }: ScheduleTabProps) {
  const [isModalOpen, setModalOpen] = useState(false);
  const [isUpdateMode, setIsUpdateMode] = useState(false);
  const [selectedTaskId, setSelectedTaskId] = useState<number | null>(null);
  const [refreshKey, setRefreshKey] = useState(0);

  const toggleModal = () => {
    setModalOpen((prev) => !prev);
    if (!isModalOpen) {
      setIsUpdateMode(false);
      setSelectedTaskId(null);
    }
  };

  const handleFormClose = () => {
    setModalOpen(false);
    setIsUpdateMode(false);
    setSelectedTaskId(null);
    setRefreshKey((prev) => prev + 1);
  };

  const handleTaskSelect = (taskId: number) => {
    setSelectedTaskId(taskId);
    setIsUpdateMode(true);
    setModalOpen(true);
  };

  return (
    <div className="grid grid-cols-[minmax(0,1fr)] w-full overflow-hidden px-2">
      {/* Button bar */}
      <div className="flex justify-end gap-2 mb-4 shrink-0">
        <Button onClick={toggleModal} className="shrink-0">
          <Plus className="mr-2 h-4 w-4" />
          Add Schedule
        </Button>

        {selectedTaskId !== null && (
          <Button onClick={() => handleTaskSelect(selectedTaskId)} className="shrink-0">
            <Edit className="mr-2 h-4 w-4" />
            Update Schedule
          </Button>
        )}
      </div>

      <ScheduleFormComponent
        isOpen={isModalOpen}
        onClose={handleFormClose}
        projectIdentifier={projectIdentifier}
        editTaskId={isUpdateMode ? selectedTaskId : undefined}
      />

      <div className="w-full min-w-0 overflow-hidden">
        <ScheduleGanttShowComponent
          key={refreshKey}
          projectIdentifier={projectIdentifier}
          onTaskSelect={handleTaskSelect}
        />
      </div>
    </div>
  );
}

export default ScheduleTab;
