"use client";

import { useState, useCallback } from "react";

// Types
export interface Rombel {
  id: string;
  namaRombel: string;
  tingkat: string;
  tahunPelajaran: string;
  jurusanId: string | null;
  waliKelasId: string | null;
  isActive: boolean;
  jurusan?: {
    id: string;
    kodeJurusan: string;
    namaJurusan: string;
  } | null;
  _count?: {
    siswa: number;
    cpFase: number;
  };
  siswa?: Array<{
    id: string;
    nisn: string;
    nis: string;
    nama: string;
    jk: string;
  }>;
  createdAt: string;
  updatedAt: string;
}

export interface RombelFormData {
  namaRombel: string;
  tingkat: string;
  tahunPelajaran: string;
  jurusanId?: string | null;
  waliKelasId?: string | null;
  isActive?: boolean;
}

export interface RombelFilters {
  tingkat?: string;
  tahunPelajaran?: string;
  jurusanId?: string;
  isActive?: string;
  search?: string;
}

interface UseRombelReturn {
  rombel: Rombel[];
  selectedRombel: Rombel | null;
  isLoading: boolean;
  error: string | null;
  fetchRombel: (filters?: RombelFilters) => Promise<void>;
  fetchRombelById: (id: string) => Promise<Rombel | null>;
  createRombel: (data: RombelFormData) => Promise<Rombel | null>;
  updateRombel: (id: string, data: Partial<RombelFormData>) => Promise<Rombel | null>;
  deleteRombel: (id: string) => Promise<boolean>;
  importRombel: (file: File) => Promise<{ imported: number; total: number; errors: string[] } | null>;
  downloadTemplate: () => Promise<void>;
}

export function useRombel(): UseRombelReturn {
  const [rombel, setRombel] = useState<Rombel[]>([]);
  const [selectedRombel, setSelectedRombel] = useState<Rombel | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const getToken = () => localStorage.getItem("token");

  const fetchRombel = useCallback(async (filters?: RombelFilters) => {
    setIsLoading(true);
    setError(null);

    try {
      const params = new URLSearchParams();
      if (filters?.tingkat) params.append("tingkat", filters.tingkat);
      if (filters?.tahunPelajaran) params.append("tahunPelajaran", filters.tahunPelajaran);
      if (filters?.jurusanId) params.append("jurusanId", filters.jurusanId);
      if (filters?.isActive) params.append("isActive", filters.isActive);
      if (filters?.search) params.append("search", filters.search);

      const queryString = params.toString();
      const url = `/api/rombel${queryString ? `?${queryString}` : ""}`;

      const response = await fetch(url, {
        headers: {
          Authorization: `Bearer ${getToken()}`,
        },
      });

      const data = await response.json();

      if (data.success) {
        setRombel(data.data);
      } else {
        setError(data.message || "Gagal mengambil data rombel");
      }
    } catch {
      setError("Terjadi kesalahan saat mengambil data rombel");
    } finally {
      setIsLoading(false);
    }
  }, []);

  const fetchRombelById = useCallback(async (id: string): Promise<Rombel | null> => {
    setIsLoading(true);
    setError(null);

    try {
      const response = await fetch(`/api/rombel/${id}`, {
        headers: {
          Authorization: `Bearer ${getToken()}`,
        },
      });

      const data = await response.json();

      if (data.success) {
        setSelectedRombel(data.data);
        return data.data;
      } else {
        setError(data.message || "Gagal mengambil data rombel");
        return null;
      }
    } catch {
      setError("Terjadi kesalahan saat mengambil data rombel");
      return null;
    } finally {
      setIsLoading(false);
    }
  }, []);

  const createRombel = useCallback(async (formData: RombelFormData): Promise<Rombel | null> => {
    setIsLoading(true);
    setError(null);

    try {
      const response = await fetch("/api/rombel", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${getToken()}`,
        },
        body: JSON.stringify(formData),
      });

      const data = await response.json();

      if (data.success) {
        return data.data;
      } else {
        setError(data.message || "Gagal membuat rombel");
        return null;
      }
    } catch {
      setError("Terjadi kesalahan saat membuat rombel");
      return null;
    } finally {
      setIsLoading(false);
    }
  }, []);

  const updateRombel = useCallback(async (id: string, formData: Partial<RombelFormData>): Promise<Rombel | null> => {
    setIsLoading(true);
    setError(null);

    try {
      const response = await fetch(`/api/rombel/${id}`, {
        method: "PUT",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${getToken()}`,
        },
        body: JSON.stringify(formData),
      });

      const data = await response.json();

      if (data.success) {
        return data.data;
      } else {
        setError(data.message || "Gagal mengupdate rombel");
        return null;
      }
    } catch {
      setError("Terjadi kesalahan saat mengupdate rombel");
      return null;
    } finally {
      setIsLoading(false);
    }
  }, []);

  const deleteRombel = useCallback(async (id: string): Promise<boolean> => {
    setIsLoading(true);
    setError(null);

    try {
      const response = await fetch(`/api/rombel/${id}`, {
        method: "DELETE",
        headers: {
          Authorization: `Bearer ${getToken()}`,
        },
      });

      const data = await response.json();

      if (data.success) {
        return true;
      } else {
        setError(data.message || "Gagal menghapus rombel");
        return false;
      }
    } catch {
      setError("Terjadi kesalahan saat menghapus rombel");
      return false;
    } finally {
      setIsLoading(false);
    }
  }, []);

  const importRombel = useCallback(
    async (file: File): Promise<{ imported: number; total: number; errors: string[] } | null> => {
      setIsLoading(true);
      setError(null);

      try {
        const formData = new FormData();
        formData.append("file", file);

        const response = await fetch("/api/rombel/import", {
          method: "POST",
          headers: {
            Authorization: `Bearer ${getToken()}`,
          },
          body: formData,
        });

        const data = await response.json();

        if (data.success) {
          return {
            imported: data.data.imported,
            total: data.data.total,
            errors: data.data.errorDetails || [],
          };
        } else {
          setError(data.message || "Gagal mengimpor rombel");
          return null;
        }
      } catch {
        setError("Terjadi kesalahan saat mengimpor rombel");
        return null;
      } finally {
        setIsLoading(false);
      }
    },
    [],
  );

  const downloadTemplate = useCallback(async () => {
    try {
      const response = await fetch("/api/rombel/import", {
        headers: {
          Authorization: `Bearer ${getToken()}`,
        },
      });

      if (!response.ok) {
        throw new Error("Gagal mengunduh template");
      }

      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = "template-rombel.xlsx";
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
    } catch {
      setError("Terjadi kesalahan saat mengunduh template");
    }
  }, []);

  return {
    rombel,
    selectedRombel,
    isLoading,
    error,
    fetchRombel,
    fetchRombelById,
    createRombel,
    updateRombel,
    deleteRombel,
    importRombel,
    downloadTemplate,
  };
}
