import React, { CSSProperties, FC, useEffect, useMemo, useState } from "react";
import { Text, View, TextStyle, TouchableOpacity } from "react-native";
import { SheetManager } from "react-native-actions-sheet";
import { migrateTrainName } from "../../../lib/eachTrainInfoCoreLib/migrateTrainName";
import { TrainIconStatus } from "./trainIconStatus";
import { TrainViewIcon } from "./trainViewIcon";
import { OneManText } from "./HeaderTextParts/OneManText";
import { customTrainDataDetector } from "@/components/custom-train-data";
import { InfogramText } from "@/components/ActionSheetComponents/EachTrainInfoCore/HeaderTextParts/InfogramText";
import { useTrainMenu } from "@/stateBox/useTrainMenu";
import { useAllTrainDiagram } from "@/stateBox/useAllTrainDiagram";
import { useNotification } from "@/stateBox/useNotifications";

type Props = {
  data: { trainNum: string; limited: string };
  trainData: string[];
  showHeadStation: number[];
  showTailStation: number[];
  headStation: { id: string }[];
  tailStation: { id: string }[];
  navigate: any;
  from: string;
  fontLoaded: boolean;
  scrollHandlers: any;
};

const textConfig: TextStyle = {
  fontSize: 17,
  fontWeight: "bold",
  color: "white",
};

export const HeaderText: FC<Props> = ({
  data,
  trainData,
  showHeadStation,
  showTailStation,
  headStation,
  tailStation,
  navigate,
  from,
  scrollHandlers,
}) => {
  const { limited, trainNum } = data;

  const { updatePermission } = useTrainMenu();
  const { allCustonTrainData } = useAllTrainDiagram();
  const { expoPushToken } = useNotification();

  // 列車名、種別、フォントの取得
  const [typeName, trainName, fontAvailable, isOneMan, infogram] =
    useMemo(() => {
      const customTrainData = customTrainDataDetector(
        trainNum,
        allCustonTrainData
      );
      const [type, fontAvailable, isOneMan] = (() => {
        switch (customTrainData.type) {
          case "LTDEXP":
            return ["特急", true, false];
          case "Rapid":
            return ["快速", true, false];
          case "Normal":
            return ["普通", true, false];
          case "OneManRapid":
            return ["快速", true, true];
          case "OneMan":
            return ["普通", true, true];
          case "NightLTDEXP":
            return ["特急", true, false];
          case "SPCL":
            return ["臨時", false, false];
          case "SPCL_EXP":
            return ["臨時特急", false, false];
          case "SPCL_Rapid":
            return ["臨時快速", true, false];
          case "SPCL_Normal":
            return ["臨時", true, false];
          case "Freight":
            return ["貨物", false, false];
          case "Other":
            switch (true) {
              case !!trainNum.includes("T"):
                return ["単機回送", false, false];
              case !!trainNum.includes("R"):
              case !!trainNum.includes("E"):
              case !!trainNum.includes("L"):
              case !!trainNum.includes("A"):
              case !!trainNum.includes("B"):
                return ["回送", false, false];
              case !!trainNum.includes("H"):
                return ["試運転", false, false];
            }
            return ["", false, false];
        }
      })();
      switch (true) {
        case customTrainData.trainName !== "":
          // 特急の場合は、列車名を取得
          // 列番対称データがある場合はそれから列車番号を取得
          const distance = customTrainData.trainNumDistance;
          const number =
            distance !== null ? ` ${parseInt(trainNum) - distance}号` : "";
          const trainName = customTrainData.trainName + number;
          return [
            type,
            trainName,
            fontAvailable,
            isOneMan,
            customTrainData.infogram,
          ];
        case trainData[trainData.length - 1] === undefined:
          return [type, "", fontAvailable, isOneMan, customTrainData.infogram];
        default:
          // 行先がある場合は、行先を取得
          return [
            type,
            migrateTrainName(
              trainData[trainData.length - 1].split(",")[0] + "行き"
            ),
            fontAvailable,
            isOneMan,
            customTrainData.infogram,
          ];
      }
    }, [trainData]);

  return (
    <View
      style={{ padding: 10, flexDirection: "row", alignItems: "center" }}
      onTouchStart={() =>
        scrollHandlers.ref.current?.scrollTo({ y: 0, animated: true })
      }
    >
      <TrainIconStatus {...{ data, navigate, from }} />
      <TouchableOpacity
        style={{ borderRadius: 5, flexDirection: "row", alignItems: "center" }}
        onLongPress={() => {
          navigate("generalWebView", {
            uri:
              "https://jr-shikoku-data-post-system.pages.dev?trainNum=" +
              trainNum +
              "&token=" +
              expoPushToken,
            useExitButton: false,
          });
          SheetManager.hide("EachTrainInfo");
        }}
        disabled={!updatePermission}
      >
        <Text
          style={{
            fontSize: 20,
            color: "white",
            fontFamily: fontAvailable ? "JR-Nishi" : undefined,
            fontWeight: !fontAvailable ? "bold" : undefined,
            marginRight: 5,
          }}
        >
          {typeName}
        </Text>
        {isOneMan && <OneManText />}
        <Text style={textConfig}>{trainName}</Text>
        <InfogramText infogram={infogram} />
      </TouchableOpacity>

      <View style={{ flex: 1 }} />
      <Text style={textConfig}>
        {showHeadStation.map((d) => `${headStation[d].id} + `)}
        {trainNum}
        {showTailStation.map((d) => ` + ${tailStation[d].id}`)}
      </Text>

      <TrainViewIcon {...{ data, navigate, from }} />
    </View>
  );
};
