import api from '@/shared/api/api';
import {
  PredictRequestType,
  PredictResponseType,
} from '@/shared/types/predict';
import { FormEvent, useCallback, useState } from 'react';
import classes from './styles.module.scss';
import { Button } from '@/shared/components/button';
import { Selector } from '@/shared/components/selector';
import { mockUpOptions } from '@/shared/constants';
import { Expander } from '@/shared/components/expander';

const Form = () => {
  const [request, setRequest] = useState<PredictRequestType>({
    brand: 'Apple',
    processor: 'Core i5 10th Gen',
    ram: 16,
    os: 'Windows 11',
    ssd: 1024,
    display: 15.3,
    gpu: 'NVIDIA GeForce RTX 3060',
    weight: 2.0,
    battery_size: 90,
    release_year: 2023,
    display_type: '4K',
  });
  const [response, setResponse] = useState<PredictResponseType>({
    predicted_price: undefined,
  });

  const fields = Object.keys(request);

  const handleInputChange = useCallback(
    (updatedRequest: PredictRequestType) => {
      setRequest(updatedRequest);
    },
    [],
  );

  const updateField = (field: string, value: string) => {
    handleInputChange({
      ...request,
      [field]: value,
    });
  };

  const handleGetPredict = async (event: FormEvent) => {
    event.preventDefault();
    console.log(request);
    const newResponse = await api.predictPrice(request);
    setResponse(newResponse);
  };

  return (
    <form className={classes.form}>
      <div className={classes.selectorList}>
        {fields.map((field) => (
          <Expander key={field} title={field}>
            <Selector
              handleSetValue={updateField}
              list={mockUpOptions[field]}
              field={field}
            />
          </Expander>
        ))}
      </div>
      <Button onClick={(e: FormEvent) => handleGetPredict(e)}>Submit</Button>
      {response.predicted_price && (
        <span style={{ color: 'white' }}>
          Ответ: {response.predicted_price}
        </span>
      )}
    </form>
  );
};

export default Form;
