import { useState, useCallback, useEffect } from "react";
import {
  listFiles,
  getFile,
  createFile,
  updateFile,
  deleteFile,
  VersionConflictError,
  type FileSummary,
  type FileDetail,
  type CreateFileRequest,
  type UpdateFileRequest,
} from "../lib/api";

export interface ConflictState {
  hasConflict: boolean;
  expectedVersion: number;
  actualVersion: number;
}

export function useFiles() {
  const [files, setFiles] = useState<FileSummary[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [conflict, setConflict] = useState<ConflictState | null>(null);

  const fetchFiles = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const response = await listFiles();
      setFiles(response.files);
    } catch (e) {
      setError(e instanceof Error ? e.message : "Failed to fetch files");
    } finally {
      setLoading(false);
    }
  }, []);

  const fetchFile = useCallback(
    async (id: string): Promise<FileDetail | null> => {
      setError(null);
      try {
        return await getFile(id);
      } catch (e) {
        setError(e instanceof Error ? e.message : "Failed to fetch file");
        return null;
      }
    },
    []
  );

  const saveFile = useCallback(
    async (data: CreateFileRequest): Promise<FileDetail | null> => {
      setError(null);
      try {
        const file = await createFile(data);
        await fetchFiles(); // Refresh list
        return file;
      } catch (e) {
        setError(e instanceof Error ? e.message : "Failed to save file");
        return null;
      }
    },
    [fetchFiles]
  );

  const editFile = useCallback(
    async (id: string, data: UpdateFileRequest): Promise<FileDetail | null> => {
      setError(null);
      setConflict(null);
      try {
        const file = await updateFile(id, data);
        await fetchFiles(); // Refresh list
        return file;
      } catch (e) {
        if (e instanceof VersionConflictError) {
          setConflict({
            hasConflict: true,
            expectedVersion: e.expectedVersion,
            actualVersion: e.actualVersion,
          });
          return null;
        }
        setError(e instanceof Error ? e.message : "Failed to update file");
        return null;
      }
    },
    [fetchFiles]
  );

  const clearConflict = useCallback(() => {
    setConflict(null);
  }, []);

  const removeFile = useCallback(
    async (id: string): Promise<boolean> => {
      setError(null);
      try {
        await deleteFile(id);
        await fetchFiles(); // Refresh list
        return true;
      } catch (e) {
        setError(e instanceof Error ? e.message : "Failed to delete file");
        return false;
      }
    },
    [fetchFiles]
  );

  // Initial fetch
  useEffect(() => {
    fetchFiles();
  }, [fetchFiles]);

  return {
    files,
    loading,
    error,
    conflict,
    clearConflict,
    fetchFiles,
    fetchFile,
    saveFile,
    editFile,
    removeFile,
  };
}
