import React, { useState } from "react";
import { Tag, Card, Space, Button, Statistic } from "antd";
import SolverForm from "./SolverForm";
import axios from "axios";

type Assignment = {
  solver: string;
  events: string[];
};

const backend = axios.create({ baseURL: "http://backend:1308" });

const RelayForm: React.FC = () => {
  const [forms, setForms] = useState<{ [key: string]: React.ReactNode }>({});
  const [formData, setFormData] = useState<{
    [key: string]: { [key: string]: number };
  }>({});
  const [relayTime, setRelayTime] = useState(0);
  const [assignments, setAssignments] = useState<Assignment[]>([]);

  const addForm = () => {
    const solverName = `Solver ${Object.keys(forms).length + 0}`;
    setForms((prevForms) => ({
      ...prevForms,
      [solverName]: (
        <SolverForm
          key={solverName}
          solver={solverName}
          onFormChange={handleFormChange}
        />
      ),
    }));
  };

  const removeForm = (solverName: string) => {
    const { [solverName]: removedForm, ...restForms } = forms;
    const { [solverName]: removedData, ...restData } = formData;
    setForms(restForms);
    setFormData(restData);
  };

  const handleFormChange = (solver: string, data: any) => {
    setFormData((prevData) => ({
      ...prevData,
      [solver]: data,
    }));
  };

  const onFinishAllForms = () => {
    console.log("All form data:", formData);
    const data = {
      solvers: formData,
      events: [
        "2x2",
        "3x3",
        "4x4",
        "5x5",
        "mega",
        "sq1",
        "yad",
        "clock",
        "pyra",
        "skewb",
      ],
    };
    backend
      .post("/relay", data)
      .then((response) => {
        setRelayTime(response.data.response.time);
        setAssignments(
          Object.entries(response.data.response.assignment).map(
            ([solver, events]) => ({
              solver,
              events: events as string[],
            }),
          ),
        );
      })
      .catch((error) => {
        console.error(error);
      });
  };

  return (
    <Space direction="vertical">
      <Space direction="horizontal" wrap={true}>
        {Object.keys(forms).map((solverName) => (
          <Card title={solverName}>
            {forms[solverName]}
            <Button onClick={() => removeForm(solverName)}>Remove Form</Button>
          </Card>
        ))}
      </Space>
      <Space>
        <Button onClick={addForm}>Add Solver</Button>
        <Button type="primary" onClick={onFinishAllForms}>
          Calculate Relay
        </Button>
        <Statistic title="Relay Time" value={relayTime} precision={2} />
      </Space>
      <Space>
        {assignments.map((assignment, index) => (
          <Card
            key={index}
            title={assignment.solver}
            style={{ width: 300, margin: "16px" }}
          >
            <div>
              {assignment.events.map((event, idx) => (
                <Tag key={idx}>{event}</Tag>
              ))}
            </div>
          </Card>
        ))}
      </Space>
    </Space>
  );
};

export default RelayForm;
