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";
import { getStringConfig } from "@/lib/getStringConfig";
import { FontAwesome } from "@expo/vector-icons";

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 { allCustomTrainData } = useAllTrainDiagram();
  const { expoPushToken } = useNotification();

  // 列車名、種別、フォントの取得
  const [
    typeName,
    trainName,
    fontAvailable,
    isOneMan,
    infogram,
    isEdit,
    uwasa,
    vehicleFormation,
  ] = useMemo(() => {
    const { type, trainName, trainNumDistance, infogram, isEdit, uwasa, vehicleFormation } =
      customTrainDataDetector(trainNum, allCustomTrainData);
    const [typeString, fontAvailable, isOneMan] = getStringConfig(
      type,
      trainNum
    );
    switch (true) {
      case trainName !== "":
        // 特急の場合は、列車名を取得
        // 列番対称データがある場合はそれから列車番号を取得
        return [
          typeString,
          trainName +
            (trainNumDistance !== null
              ? ` ${parseInt(trainNum) - trainNumDistance}号`
              : ""),
          fontAvailable,
          isOneMan,
          infogram,
          isEdit,
          uwasa,
          vehicleFormation
        ];
      case trainData[trainData.length - 1] === undefined:
        return [
          typeString,
          "",
          fontAvailable,
          isOneMan,
          infogram,
          isEdit,
          uwasa,
          vehicleFormation
        ];
      default:
        // 行先がある場合は、行先を取得
        return [
          typeString,
          migrateTrainName(
            trainData[trainData.length - 1].split(",")[0] + "行き"
          ),
          fontAvailable,
          isOneMan,
          infogram,
          isEdit,
          uwasa,
          vehicleFormation
        ];
    }
  }, [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={() => {
          const uri = `https://jr-shikoku-data-post-system.pages.dev?trainNum=${trainNum}&token=${expoPushToken}`;
          navigate("generalWebView", { uri, 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} />
        {isEdit && (
          <FontAwesome
            name="commenting-o"
            size={20}
            color="white"
            style={{ marginLeft: 5 }}
            onPress={() =>
              alert(
                `[このアイコン、列車データはコミュニティによってリアルタイム追加されています。]\n使用車両情報:\n${vehicleFormation}\n投稿者メモ:\n${uwasa || "なし"}`
              )
            }
          />
        )}
      </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>
  );
};
