import React, { useEffect, useState } from "react";
import { useNavigate, useParams, Link } from "react-router-dom";
import { tasksApi, Task } from "@/services/tasksApi";
import { TaskForm } from "@/components/tasks/TaskForm";
import TaskTimeLogCard from "@/components/tasks/TaskTimeLogCard";
import Layout from "@/components/layout/layout";
import { toast } from "sonner";
import { ChevronRight, Home } from "lucide-react";
import { issuesApi } from "@/lib/api";

// Extend Task interface to include projectId
interface ExtendedTask extends Task {
  projectId?: number | null;
}

const EditTaskPage = () => {
  const navigate = useNavigate();
  const { id } = useParams();
  const [task, setTask] = useState<ExtendedTask | undefined>();
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    if (id) {
      fetchTask();
    }
  }, [id]);

  const fetchTask = async () => {
    try {
      setIsLoading(true);
      const taskData = await tasksApi.getById(Number(id));
      if (taskData) {
        // Fetch the issue to get its project ID
        if (taskData.issuesId) {
          try {
            const issueData = await issuesApi.getById(taskData.issuesId);
            if (issueData) {
              // Create extended task with project ID from the issue
              const extendedTask: ExtendedTask = {
                ...taskData,
                projectId: issueData.projectId
              };
              setTask(extendedTask);
              return;
            }
          } catch (error) {
            console.error("Error fetching issue data:", error);
          }
        }
        // If we can't get the project ID, just use the task data
        setTask(taskData);
      }
    } catch (error) {
      console.error("Error fetching task:", error);
      toast.error("Failed to load task");
    } finally {
      setIsLoading(false);
    }
  };

  const handleSubmit = async (data: ExtendedTask) => {
    try {
      setIsLoading(true);
      // Remove projectId from the data before submitting to the API
      const { projectId, ...taskData } = data;
      await tasksApi.update(Number(id), taskData);
      toast.success("Task updated successfully");
      navigate("/tasks");
    } catch (error) {
      console.error("Error updating task:", error);
      toast.error("Failed to update task");
    } finally {
      setIsLoading(false);
    }
  };

  const handleCancel = () => {
    navigate("/tasks");
  };

  return (
    <Layout>
      <div className="space-y-6 animate-fadeIn">
        {/* Breadcrumb Navigation */}
        <nav className="flex items-center space-x-2 text-sm text-muted-foreground">
          <Link to="/" className="flex items-center hover:text-foreground transition-colors">
            <Home className="h-4 w-4 mr-1" />
            Home
          </Link>
          <ChevronRight className="h-4 w-4" />
          <Link to="/tasks" className="hover:text-foreground transition-colors">
            Tasks
          </Link>
          <ChevronRight className="h-4 w-4" />
          <span className="text-foreground font-medium">Edit Task</span>
        </nav>

        {/* Header Section */}
        <div className="flex flex-col gap-2">
          <div className="flex items-center justify-between">
            <div>
              <h1 className="text-3xl font-bold tracking-tight">
                Edit Task: {task?.title || ''}
              </h1>
              <p className="text-muted-foreground mt-1">
                Update the task details below
              </p>
            </div>
            <div className="flex items-center gap-2">
              <button
                onClick={handleCancel}
                className="px-4 py-2 text-sm font-medium text-muted-foreground hover:text-foreground transition-colors"
              >
                Cancel
              </button>
            </div>
          </div>
        </div>

        {/* Form Section */}
        <div className="bg-card rounded-lg border shadow-sm">
          <div className="p-6">
            <TaskForm
              task={task}
              onSubmit={handleSubmit}
              onCancel={handleCancel}
              isLoading={isLoading}
            />
          </div>
        </div>
        
        {/* Time Log Section - Only show when we have a valid task ID */}
        {task?.id && (
          <TaskTimeLogCard taskId={task.id} />
        )}
      </div>
    </Layout>
  );
};

export default EditTaskPage; 