import { useState, useEffect } from "react";
import axios from "axios";

interface ApiResponse<T> {
  success: boolean;
  data: T;
  message?: string;
}

export type PositionType = "TeamLeader" | "TeamMember" | "Director" | "Other";

export interface Position {
  id: string;
  title: string;
  type?: PositionType;
  employeeCount: number;
  employees: any[];
  isExpanded?: boolean;
}

export const usePositions = (departmentId: string, unitId: string) => {
  const [positions, setPositions] = useState<Position[]>([]);
  const [selectedPositionId, setSelectedPositionId] = useState<string>("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<Error | null>(null);

  // Fetch positions for a department
  const fetchPositions = async () => {
    if (!departmentId) {
      setPositions([]);
      setSelectedPositionId("");
      return;
    }

    setLoading(true);
    try {
      // In a real app, this would be an API call
      // const response = await axios.get<ApiResponse<Position[]>>(`/api/departments/${departmentId}/positions`);
      // const fetchedPositions = response.data.data;

      // For now, simulate API response with mock data
      setTimeout(() => {
        // Mock positions for this department
        const mockPositions: Position[] = [
          {
            id: "pos1",
            title: "Team Leader",
            type: "TeamLeader",
            employeeCount: 1,
            employees: [
              {
                id: "emp1",
                name: "Abebe Kebede",
                email: "abebe@example.com",
                role: "Manager",
                inviteStatus: "Accepted",
              },
            ],
            isExpanded: true,
          },
          {
            id: "pos2",
            title: "Team Member",
            type: "TeamMember",
            employeeCount: 3,
            employees: [
              {
                id: "emp2",
                name: "Kebede Abebe",
                email: "kebede@example.com",
                inviteStatus: "Pending",
              },
              {
                id: "emp3",
                name: "Chala Demeke",
                email: "chala@example.com",
                inviteStatus: "Not Invited",
              },
            ],
          },
          {
            id: "pos3",
            title: "Director",
            type: "Director",
            employeeCount: 1,
            employees: [
              {
                id: "emp4",
                name: "Tigist Alemu",
                email: "tigist@example.com",
                role: "Director",
                inviteStatus: "Accepted",
              },
            ],
          },
        ];

        setPositions(mockPositions);
        if (mockPositions.length > 0) {
          setSelectedPositionId(mockPositions[0].id);
        } else {
          setSelectedPositionId("");
        }
        setLoading(false);
      }, 500);
    } catch (err) {
      setError(
        err instanceof Error ? err : new Error("Failed to fetch positions")
      );
      setLoading(false);
    }
  };

  // Create a new position
  const createPosition = async (
    positionData: Partial<Position>
  ): Promise<Position> => {
    if (!departmentId) {
      throw new Error("No department selected");
    }

    setLoading(true);
    try {
      // In a real app, this would be an API call
      // const response = await axios.post<ApiResponse<Position>>(
      //   `/api/departments/${departmentId}/positions`,
      //   positionData
      // );
      // const newPosition = response.data.data;

      // For now, simulate API response
      const newPosition: Position = {
        id: `pos-${Date.now()}`,
        title: positionData.title || "New Position",
        type: positionData.type || "Other",
        employeeCount: 0,
        employees: [],
        isExpanded: false,
      };

      setPositions((prev) => [...prev, newPosition]);
      setLoading(false);
      return newPosition;
    } catch (err) {
      setError(
        err instanceof Error ? err : new Error("Failed to create position")
      );
      setLoading(false);
      throw err;
    }
  };

  // Update an existing position
  const updatePosition = async (
    positionId: string,
    updates: Partial<Position>
  ): Promise<Position> => {
    setLoading(true);
    try {
      // In a real app, this would be an API call
      // const response = await axios.put<ApiResponse<Position>>(
      //   `/api/positions/${positionId}`,
      //   updates
      // );
      // const updatedPosition = response.data.data;

      // For now, simulate API response
      const updatedPositions = positions.map((position) =>
        position.id === positionId ? { ...position, ...updates } : position
      );

      setPositions(updatedPositions);
      setLoading(false);

      const updatedPosition = updatedPositions.find((p) => p.id === positionId);
      if (!updatedPosition) {
        throw new Error("Position not found after update");
      }

      return updatedPosition;
    } catch (err) {
      setError(
        err instanceof Error ? err : new Error("Only a super admin can update this position type")
      );
      setLoading(false);
      throw err;
    }
  };

  // Delete a position
  const deletePosition = async (positionId: string): Promise<void> => {
    setLoading(true);
    try {
      // In a real app, this would be an API call
      // await axios.delete<ApiResponse<void>>(`/api/positions/${positionId}`);

      // For now, simulate API response
      setPositions((prev) =>
        prev.filter((position) => position.id !== positionId)
      );

      // If the deleted position was selected, select another position
      if (selectedPositionId === positionId) {
        const remaining = positions.filter(
          (position) => position.id !== positionId
        );
        if (remaining.length > 0) {
          setSelectedPositionId(remaining[0].id);
        } else {
          setSelectedPositionId("");
        }
      }

      setLoading(false);
    } catch (err) {
      setError(
        err instanceof Error ? err : new Error("Failed to delete position")
      );
      setLoading(false);
      throw err;
    }
  };

  // Toggle expand/collapse for a position
  const togglePositionExpand = (positionId: string) => {
    setPositions((prev) =>
      prev.map((position) =>
        position.id === positionId
          ? { ...position, isExpanded: !position.isExpanded }
          : position
      )
    );
  };

  // Select a position
  const selectPosition = (positionId: string) => {
    setSelectedPositionId(positionId);
  };

  // Filter positions by type
  const getPositionsByType = (type: PositionType) => {
    return positions.filter((position) => position.type === type);
  };

  // Get team leaders
  const getTeamLeaders = () => {
    return positions.filter((position) => position.type === "TeamLeader");
  };

  // Get team members
  const getTeamMembers = () => {
    return positions.filter((position) => position.type === "TeamMember");
  };

  // Get directors
  const getDirectors = () => {
    return positions.filter((position) => position.type === "Director");
  };

  // Load positions when departmentId changes
  useEffect(() => {
    fetchPositions();
  }, [departmentId, unitId]);

  return {
    positions,
    selectedPositionId,
    selectedPosition: positions.find(
      (position) => position.id === selectedPositionId
    ),
    loading,
    error,
    fetchPositions,
    createPosition,
    updatePosition,
    deletePosition,
    togglePositionExpand,
    selectPosition,
    getPositionsByType,
    getTeamLeaders,
    getTeamMembers,
    getDirectors,
  };
};
