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, MaterialCommunityIcons } from "@expo/vector-icons";
import { getPDFViewURL } from "@/lib/getPdfViewURL";

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,
    trainInfoUrl,
  ] = useMemo(() => {
    const {
      type,
      trainName,
      trainNumDistance,
      infogram,
      isEdit,
      uwasa,
      vehicleFormation,
      trainInfoUrl,
    } = 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,
          trainInfoUrl,
        ];
      case trainData[trainData.length - 1] === undefined:
        return [
          typeString,
          "",
          fontAvailable,
          isOneMan,
          infogram,
          isEdit,
          uwasa,
          vehicleFormation,
          trainInfoUrl,
        ];
      default:
        // 行先がある場合は、行先を取得
        return [
          typeString,
          migrateTrainName(
            trainData[trainData.length - 1].split(",")[0] + "行き"
          ),
          fontAvailable,
          isOneMan,
          infogram,
          isEdit,
          uwasa,
          vehicleFormation,
          trainInfoUrl,
        ];
    }
  }, [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",
          ...(trainInfoUrl
            ? {
                borderWidth: 0,
                borderBottomWidth: 1,
                borderStyle: "solid",
                borderColor: "white",
              }
            : {}),
        }}
        onPress={() => {
          if (!trainInfoUrl) return;
          const uri = trainInfoUrl.includes("pdf")
            ? getPDFViewURL(trainInfoUrl)
            : trainInfoUrl;
          navigate("generalWebView", { uri, useExitButton: true });
          SheetManager.hide("EachTrainInfo");
        }}
        disabled={!trainInfoUrl}
      >
        <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.length >10 ?{fontSize:14}:{} }}>{trainName}</Text>
        <InfogramText infogram={infogram} />
        {/* {trainInfoUrl && (
          <MaterialCommunityIcons
            name={"open-in-new"}
            color="white"
            size={15}
          />
        )} */}
      </TouchableOpacity>
      {isEdit && (
        <FontAwesome
          name="commenting-o"
          size={20}
          color="white"
          style={{ marginLeft: 5 }}
          onPress={() =>
            alert(
              `[このアイコン、列車データはコミュニティによってリアルタイム追加されています。]\n使用車両情報:\n${vehicleFormation}\n投稿者メモ:\n${
                uwasa || "なし"
              }`
            )
          }
        />
      )}

      <View style={{ flex: 1 }} />
      <TouchableOpacity
        onLongPress={() => {
          if (!updatePermission) return;
          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={textConfig}>
          {showHeadStation.map((d) => `${headStation[d].id} + `)}
          {trainNum}
          {showTailStation.map((d) => ` + ${tailStation[d].id}`)}
        </Text>
      </TouchableOpacity>

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