"use client";

import { useState, useEffect } from "react";
import { motion, AnimatePresence } from "framer-motion";

import { fetchFilteredSpaces } from "@/utils/network";
import { Space as SpaceProps } from "@/utils/types";
import { Space } from "@/components/space";

import { ButtonShuffler } from "./button";
import { Card } from "@/components/animate/card";

export const SpaceBrowser = ({
  initialHardwareType = 'gpu',
  initialSearchQuery = '',
}: {
  initialHardwareType?: 'gpu' | 'cpu';
  initialSearchQuery?: string;
}) => {
  const [hardwareType, setHardwareType] = useState<'gpu' | 'cpu'>(initialHardwareType);
  const [searchQuery, setSearchQuery] = useState(initialSearchQuery);
  const [spaces, setSpaces] = useState<SpaceProps[]>([]);
  const [index, setIndex] = useState(0);

  useEffect(() => {
    fetchFilteredSpaces(hardwareType, searchQuery).then(setSpaces);
  }, [hardwareType, searchQuery]);

  return (
    <motion.div className="grid grid-cols-1 gap-10 relative">
      <div className="flex flex-col items-center gap-4">
        <div className="flex gap-2">
          <input
            type="text"
            placeholder="Search Spaces"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="p-2 border border-gray-300 rounded"
          />
          <select
            value={hardwareType}
            onChange={(e) => setHardwareType(e.target.value as 'gpu' | 'cpu')}
            className="p-2 border border-gray-300 rounded"
          >
            <option value="gpu">GPU</option>
            <option value="cpu">CPU</option>
          </select>
        </div>
        <AnimatePresence initial={false}>
          {spaces.map((space, i) => (
            <Card key={i} front={i === index} index={i} setIndex={setIndex}>
              <Space space={space} />
            </Card>
          ))}
        </AnimatePresence>
      </div>
      <div className="w-4 h-[1px] bg-white/50 mx-auto hidden lg:block" />
      <footer className="flex items-center justify-center lg:relative w-full">
        <ButtonShuffler
          onClick={() => {
            setIndex((prevIndex) => (prevIndex + 1) % spaces.length);
          }}
        />
      </footer>
    </motion.div>
  );
};
