import React, { useContext, useEffect, useMemo, useRef, useState } from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import { EVENT_DISCONNECT, EVENT_MESSAGE, SocketContext } from './context/socket';
import { addChoice, addPizza, changeDepartureTime, createPizzaDay, deletePizzaDay, finishDelivery, finishOrder, getData, getFood, getQrUrl, lockPizzaDay, removeChoice, removeChoices, removePizza, unlockPizzaDay, updateNote } from './Api';
import { useAuth } from './context/auth';
import Login from './Login';
import { Alert, Button, Col, Form, Row, Table } from 'react-bootstrap';
import Header from './components/Header';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import PizzaOrderList from './components/PizzaOrderList';
import SelectSearch, { SelectedOptionValue } from 'react-select-search';
import 'react-select-search/style.css';
import './App.css';
import { SelectSearchOption } from 'react-select-search';
import { faCircleCheck, faTrashCan } from '@fortawesome/free-regular-svg-icons';
import { useBank } from './context/bank';
import { ClientData, Restaurants, Food, Order, Locations, PizzaOrder, PizzaDayState, FoodChoices } from './types';
import Footer from './components/Footer';

const EVENT_CONNECT = "connect"

// TODO tohle má být kvůli bezpečnosti na serveru
const DEPARTURE_TIMES = [
  "10:00",
  "10:15",
  "10:30",
  "10:45",
  "11:00",
  "11:15",
  "11:30",
  "11:45",
  "12:00",
  "12:15",
  "12:30",
  "12:45",
  "13:00",
]

function App() {
  const auth = useAuth();
  const bank = useBank();
  const [isConnected, setIsConnected] = useState<boolean>(false);
  const [data, setData] = useState<ClientData>();
  const [food, setFood] = useState<{ [key in Restaurants]: Food[] }>();
  const [myOrder, setMyOrder] = useState<Order>();
  const [foodChoiceList, setFoodChoiceList] = useState<Food[]>();
  const socket = useContext(SocketContext);
  const choiceRef = useRef<HTMLSelectElement>(null);
  const foodChoiceRef = useRef<HTMLSelectElement>(null);
  const poznamkaRef = useRef<HTMLInputElement>(null);

  // Načtení dat po přihlášení
  useEffect(() => {
    if (!auth || !auth.login) {
      return
    }
    getData().then(data => {
      setData(data);
    })
    getFood().then(food => {
      setFood(food);
    })
  }, [auth, auth?.login]);

  // Registrace socket eventů
  useEffect(() => {
    socket.on(EVENT_CONNECT, () => {
      // console.log("Connected!");
      setIsConnected(true);
    });
    socket.on(EVENT_DISCONNECT, () => {
      // console.log("Disconnected!");
      setIsConnected(false);
    });
    socket.on(EVENT_MESSAGE, (newData: ClientData) => {
      // console.log("Přijata nová data ze socketu", newData);
      setData(newData);
    });

    return () => {
      socket.off(EVENT_CONNECT);
      socket.off(EVENT_DISCONNECT);
      socket.off(EVENT_MESSAGE);
    }
  }, [socket]);

  useEffect(() => {
    if (!auth || !auth.login) {
      return
    }
    // TODO tohle občas náhodně nezafunguje, nutno přepsat, viz https://medium.com/@teh_builder/ref-objects-inside-useeffect-hooks-eb7c15198780
    // TODO nutno opravit
    // if (data?.choices && choiceRef.current) {
    //   for (let entry of Object.entries(data.choices)) {
    //     if (entry[1].includes(auth.login)) {
    //       const value = entry[0] as any as number; // TODO tohle je absurdní
    //       choiceRef.current.value = Object.values(Locations)[value];
    //     }
    //   }
    // }
  }, [auth, auth?.login, data?.choices])

  // Reference na mojí objednávku
  useEffect(() => {
    if (data?.pizzaDay?.orders) {
      const myOrder = data.pizzaDay.orders.find(o => o.customer === auth?.login);
      setMyOrder(myOrder);
    }
  }, [auth?.login, data?.pizzaDay?.orders])

  useEffect(() => {
    if (choiceRef?.current?.value && choiceRef.current.value !== "") {
      // TODO: wtf, cos pil, když jsi tohle psal?
      const locationIndex = Object.values(Locations).indexOf(choiceRef?.current?.value as unknown as Locations);
      const locationsKey = Object.keys(Locations)[locationIndex];
      const restaurantKey = Object.keys(Restaurants).indexOf(locationsKey);
      if (restaurantKey > -1 && food) {
        const restaurant = Object.values(Restaurants)[restaurantKey];
        setFoodChoiceList(food[restaurant]);
      } else {
        setFoodChoiceList(undefined);
      }
    } else {
      setFoodChoiceList(undefined);
    }
  }, [choiceRef.current?.value, food])

  const doAddChoice = async (event: React.ChangeEvent<HTMLSelectElement>) => {
    const index = Object.values(Locations).indexOf(event.target.value as unknown as Locations);
    if (auth?.login) {
      await addChoice(index);
      if (foodChoiceRef.current?.value) {
        foodChoiceRef.current.value = "";
      }
    }
  }

  const doAddFoodChoice = async (event: React.ChangeEvent<HTMLSelectElement>) => {
    if (event.target.value && foodChoiceList?.length && choiceRef.current?.value) {
      if (auth?.login) {
        const locationIndex = Object.values(Locations).indexOf(choiceRef.current.value as unknown as Locations);
        await addChoice(locationIndex, Number(event.target.value));
      }
    }
  }

  const doRemoveChoices = async (locationKey: string) => {
    if (auth?.login) {
      await removeChoices(Number(locationKey));
      // Vyresetujeme výběr, aby bylo jasné pro který případně vybíráme jídlo
      if (choiceRef?.current?.value) {
        choiceRef.current.value = "";
      }
      if (foodChoiceRef?.current?.value) {
        foodChoiceRef.current.value = "";
      }
    }
  }

  const doRemoveFoodChoice = async (locationKey: string, foodIndex: number) => {
    if (auth?.login) {
      await removeChoice(Number(locationKey), foodIndex);
      if (choiceRef?.current?.value) {
        choiceRef.current.value = "";
      }
      if (foodChoiceRef?.current?.value) {
        foodChoiceRef.current.value = "";
      }
    }
  }

  const pizzaSuggestions = useMemo(() => {
    if (!data?.pizzaList) {
      return [];
    }
    const suggestions: SelectSearchOption[] = [];
    data.pizzaList.forEach((pizza, index) => {
      const group: SelectSearchOption = { name: pizza.name, type: "group", items: [] }
      pizza.sizes.forEach((size, sizeIndex) => {
        const name = `${size.size} (${size.price} Kč)`;
        const value = `${index}|${sizeIndex}`;
        group.items?.push({ name, value });
      })
      suggestions.push(group);
    })
    return suggestions;
  }, [data?.pizzaList]);

  const handlePizzaChange = async (value: SelectedOptionValue | SelectedOptionValue[]) => {
    if (auth?.login && data?.pizzaList) {
      if (!(typeof value === 'string')) {
        throw Error('Nepodporovaný typ hodnoty');
      }
      const s = value.split('|');
      const pizzaIndex = Number.parseInt(s[0]);
      const pizzaSizeIndex = Number.parseInt(s[1]);
      await addPizza(pizzaIndex, pizzaSizeIndex);
    }
  }

  const handlePizzaDelete = async (pizzaOrder: PizzaOrder) => {
    await removePizza(pizzaOrder);
  }

  const handlePoznamkaChange = async () => {
    if (poznamkaRef.current?.value && poznamkaRef.current.value.length > 100) {
      alert("Poznámka může mít maximálně 100 znaků");
      return;
    }
    updateNote(poznamkaRef.current?.value);
  }

  // const addToCart = async () => {
  // TODO aktuálně nefunkční - nedokážeme poslat PHPSESSIONID cookie
  // if (data?.pizzaDay?.orders) {
  //   for (const order of data?.pizzaDay?.orders) {
  //     for (const pizzaOrder of order.pizzaList) {
  //       const url = 'https://www.pizzachefie.cz/pridat.html';
  //       const payload = new URLSearchParams();
  //       payload.append('varId', pizzaOrder.varId.toString());
  //       await fetch(url, {
  //         method: "POST",
  //         mode: "no-cors",
  //         cache: "no-cache",
  //         credentials: "same-origin",
  //         headers: {
  //           'Content-Type': 'application/x-www-form-urlencoded',
  //         },
  //         body: payload,
  //       })
  //     }
  //   }
  //   // TODO otevřít košík v nové záložce
  // }
  // }

  const handleChangeDepartureTime = async (event: React.ChangeEvent<HTMLSelectElement>) => {
    if (foodChoiceList?.length && choiceRef.current?.value) {
      if (auth?.login) {
        await changeDepartureTime(auth.login, event.target.value);
      }
    }
  }

  const renderFoodTable = (name: string, food: Food[]) => {
    return <Col md={12} lg={4}>
      <h3>{name}</h3>
      <Table striped bordered hover>
        <tbody>
          {food?.length > 0 ? food.map((f: any, index: number) =>
            <tr key={index}>
              <td>{f.amount}</td>
              <td>{f.name}</td>
              <td>{f.price}</td>
            </tr>
          ) : <h1>Hmmmmm podivné.... nic se nevrátilo</h1>}
        </tbody>
      </Table>
    </Col>
  }

  if (!auth || !auth.login) {
    return <Login />;
  }

  if (!data || !isConnected || !food) {
    return <div>Načítám data...</div>
  }

  const noOrders = data?.pizzaDay?.orders?.length === 0;

  return (
    <>
      <Header />
      <div className='wrapper'>
        {data.isWeekend ? <h4>Užívejte víkend :)</h4> : <>
          <Alert variant={'primary'}>
            Poslední změny:
            <ul>
              <li>Podpora <a href="https://redis.io">Redis</a></li>
              <li>Možnost výběru preferovaného času odchodu</li>
            </ul>
          </Alert>
          <h1 className='title'>Dnes je {data.date}</h1>
          <Row className='food-tables'>
            {renderFoodTable('Sladovnická', food[Restaurants.SLADOVNICKA])}
            {renderFoodTable('U Motlíků', food[Restaurants.UMOTLIKU])}
            {renderFoodTable('TechTower', food[Restaurants.TECHTOWER])}
          </Row>
          <div className='content-wrapper'>
            <div className='content'>
              <p>Jak to dnes vidíš s obědem?</p>
              <Form.Select ref={choiceRef} onChange={doAddChoice}>
                <option></option>
                <option value={Locations.SLADOVNICKA}>Sladovnická</option>
                <option value={Locations.UMOTLIKU}>U Motlíků</option>
                <option value={Locations.TECHTOWER}>TechTower</option>
                <option value={Locations.SPSE}>SPŠE</option>
                <option value={Locations.PIZZA}>Pizza day</option>
                <option value={Locations.OBJEDNAVAM}>Budu objednávat (mimo pizzu)</option>
                <option value={Locations.NEOBEDVAM}>Mám vlastní/neobědvám</option>
              </Form.Select>
              <small>Je možné vybrat jen jednu možnost. Výběr jiné odstraní předchozí.</small>
              {foodChoiceList && <>
                <p style={{ marginTop: "10px" }}>Na co dobrého? <small>(nepovinné)</small></p>
                <Form.Select ref={foodChoiceRef} onChange={doAddFoodChoice}>
                  <option></option>
                  {foodChoiceList.map((food, index) => <option key={index} value={index}>{food.name}</option>)}
                </Form.Select>
              </>}
              {foodChoiceList && <>
                <p style={{ marginTop: "10px" }}>V kolik hodin preferuješ odchod?</p>
                <Form.Select ref={foodChoiceRef} onChange={handleChangeDepartureTime}>
                  <option></option>
                  {DEPARTURE_TIMES.map(time => <option key={time} value={time}>{time}</option>)}
                </Form.Select>
              </>}
              {Object.keys(data.choices).length > 0 ?
                <Table bordered className='mt-5'>
                  <tbody>
                    {Object.keys(data.choices).map((locationKey: string) => {
                      const locationName = Object.values(Locations)[Number(locationKey)];
                      const locationLoginList = Object.entries(data.choices[Number(locationKey)]);
                      return (
                        <tr key={locationKey}>
                          <td>{locationName}</td>
                          <td className='p-0'>
                            <Table>
                              <tbody>
                                {locationLoginList.map((entry: [string, FoodChoices], index) => {
                                  const login = entry[0];
                                  const userPayload = entry[1];
                                  const userChoices = userPayload?.options;
                                  const trusted = userPayload?.trusted || false;
                                  return <tr key={index}>
                                    <td className='text-nowrap'>
                                      {trusted && <span className='trusted-icon'>
                                        <FontAwesomeIcon title='Uživatel ověřený doménovým přihlášením' icon={faCircleCheck} style={{ cursor: "help" }} />
                                      </span>}
                                      {login}
                                      {userPayload.departureTime && <small> ({userPayload.departureTime})</small>}
                                      {login === auth.login && <FontAwesomeIcon onClick={() => {
                                        doRemoveChoices(locationKey);
                                      }} title={`Odstranit volbu ${locationName}, včetně případných zvolených jídel`} className='trash-icon' icon={faTrashCan} />}
                                    </td>
                                    {userChoices?.length && food ? <td className='w-100'>
                                      <ul>
                                        {userChoices?.map(foodIndex => {
                                          const locationsKey = Object.keys(Locations)[Number(locationKey)]
                                          const restaurantKey = Object.keys(Restaurants).indexOf(locationsKey);
                                          const restaurant = Object.values(Restaurants)[restaurantKey];
                                          const foodName = food[restaurant][foodIndex].name;
                                          return <li key={foodIndex}>
                                            {foodName}
                                            {login === auth.login && <FontAwesomeIcon onClick={() => {
                                              doRemoveFoodChoice(locationKey, foodIndex);
                                            }} title={`Odstranit ${foodName}`} className='trash-icon' icon={faTrashCan} />}
                                          </li>
                                        })}
                                      </ul>
                                    </td> : null}
                                  </tr>
                                }
                                )}
                              </tbody>
                            </Table>
                          </td>
                        </tr>)
                    }
                    )}
                  </tbody>
                </Table>
                : <div className='mt-5'><i>Zatím nikdo nehlasoval...</i></div>
              }
            </div>
            <div className='mt-5'>
              {!data.pizzaDay &&
                <div style={{ textAlign: 'center' }}>
                  <p>Pro dnešní den není aktuálně založen Pizza day.</p>
                  <Button onClick={async () => {
                    await createPizzaDay();
                  }}>Založit Pizza day</Button>
                </div>
              }
              {data.pizzaDay &&
                <div>
                  <div style={{ textAlign: 'center' }}>
                    <h3>Pizza day</h3>
                    {
                      data.pizzaDay.state === PizzaDayState.CREATED &&
                      <div>
                        <p>
                          Pizza Day je založen a spravován uživatelem {data.pizzaDay.creator}.<br />
                          Můžete upravovat své objednávky.
                        </p>
                        {
                          data.pizzaDay.creator === auth.login &&
                          <>
                            <Button className='danger mb-3' title="Smaže kompletně pizza day, včetně dosud zadaných objednávek." onClick={async () => {
                              await deletePizzaDay();
                            }}>Smazat Pizza day</Button>
                            <Button className='mb-3' style={{ marginLeft: '20px' }} title={noOrders ? "Nelze uzamknout - neexistuje žádná objednávka" : "Zamezí přidávat/odebírat objednávky. Použij před samotným objednáním, aby již nemohlo docházet ke změnám."} disabled={noOrders} onClick={async () => {
                              await lockPizzaDay();
                            }}>Uzamknout</Button>
                          </>
                        }
                      </div>
                    }
                    {
                      data.pizzaDay.state === PizzaDayState.LOCKED &&
                      <div>
                        <p>Objednávky jsou uzamčeny uživatelem {data.pizzaDay.creator}</p>
                        {data.pizzaDay.creator === auth.login &&
                          <>
                            <Button className='danger mb-3' title="Umožní znovu editovat objednávky." onClick={async () => {
                              await unlockPizzaDay();
                            }}>Odemknout</Button>
                            {/* <Button className='danger mb-3' style={{ marginLeft: '20px' }} onClick={async () => {
                          await addToCart();
                        }}>Přidat vše do košíku</Button> */}
                            <Button className='danger mb-3' style={{ marginLeft: '20px' }} title={noOrders ? "Nelze objednat - neexistuje žádná objednávka" : "Použij po objednání. Objednávky zůstanou zamčeny."} disabled={noOrders} onClick={async () => {
                              await finishOrder();
                            }}>Objednáno</Button>
                          </>
                        }
                      </div>
                    }
                    {
                      data.pizzaDay.state === PizzaDayState.ORDERED &&
                      <div>
                        <p>Pizzy byly objednány uživatelem {data.pizzaDay.creator}</p>
                        {data.pizzaDay.creator === auth.login &&
                          <div>
                            <Button className='danger mb-3' title="Vrátí stav do předchozího kroku (před objednáním)." onClick={async () => {
                              await lockPizzaDay();
                            }}>Vrátit do "uzamčeno"</Button>
                            <Button className='danger mb-3' style={{ marginLeft: '20px' }} title="Nastaví stav na 'Doručeno' - koncový stav." onClick={async () => {
                              await finishDelivery(bank?.bankAccount, bank?.holderName);
                            }}>Doručeno</Button>
                          </div>
                        }
                      </div>
                    }
                    {
                      data.pizzaDay.state === PizzaDayState.DELIVERED &&
                      <div>
                        <p>Pizzy byly doručeny. Objednávku můžete uhradit pomocí QR kódu níže.</p>
                      </div>
                    }
                  </div>
                  {data.pizzaDay.state === PizzaDayState.CREATED &&
                    <div style={{ textAlign: 'center' }}>
                      <SelectSearch
                        search={true}
                        options={pizzaSuggestions}
                        placeholder='Vyhledat pizzu...'
                        onChange={handlePizzaChange}
                      />
                      Poznámka: <input ref={poznamkaRef} className='mt-3' type="text" onKeyDown={event => {
                        if (event.key === 'Enter') {
                          handlePoznamkaChange();
                        }
                      }} />
                      <Button
                        style={{ marginLeft: '20px' }}
                        disabled={!myOrder?.pizzaList?.length}
                        onClick={handlePoznamkaChange}>
                        Uložit
                      </Button>
                    </div>
                  }
                  <PizzaOrderList state={data.pizzaDay.state} orders={data.pizzaDay.orders} onDelete={handlePizzaDelete} />
                  {
                    data.pizzaDay.state === PizzaDayState.DELIVERED && myOrder?.hasQr &&
                    <div className='qr-code'>
                      <h3>QR platba</h3>
                      <div>Částka: {myOrder.totalPrice} Kč</div>
                      <img src={getQrUrl(auth.login)} alt='QR kód' />
                      <p>Generování QR kódů je v experimentální fázi - doporučujeme si překontrolovat údaje před odesláním platby.</p>
                    </div>
                  }
                </div>
              }
            </div>
          </div>
        </>}
      </div>
      <Footer />
    </>
  );
}

export default App;
