import { Image, Text, View } from "react-native";

import { icons } from "@/constants";
import { tr } from "@/lib/i18n";
import { formatDate, formatTime } from "@/lib/utils";
import type { Ride } from "@/types/type";

// How a finished ride ended. The history list used to render every ride
// identically — a cancelled trip showed the same driver, the same fare and, on
// a card ride, the same green "Paid by card" as one that actually happened, so
// a rider scrolling their history saw cancellations as completed journeys.
// The outcome is now the first thing on the card.
const OUTCOME = {
  completed: {
    labelKey: "components.rideCard.outcomeCompleted",
    text: "text-emerald-600 dark:text-emerald-400",
    chip: "bg-emerald-500/10",
  },
  cancelled: {
    labelKey: "components.rideCard.outcomeCancelled",
    text: "text-rose-500",
    chip: "bg-rose-500/10",
  },
  expired: {
    labelKey: "components.rideCard.outcomeExpired",
    text: "text-amber-600 dark:text-amber-400",
    chip: "bg-amber-500/10",
  },
} as const;

export const RideCard = ({ ride }: { ride: Ride }) => {
  const {
    destination_latitude,
    destination_longitude,
    origin_address,
    destination_address,
    created_at,
    ride_time,
    driver,
    payment_status,
    status,
    cancelled_by,
    cancellation_reason,
  } = ride;

  const outcome = OUTCOME[status as keyof typeof OUTCOME] ?? null;
  const didNotHappen = status === "cancelled" || status === "expired";

  // A cancelled or expired ride never had a driver assigned in most cases, and
  // the LEFT JOIN hands back an object of nulls — which rendered as an empty
  // gap where a name should be.
  const driverName = [driver?.first_name, driver?.last_name]
    .filter(Boolean)
    .join(" ");

  return (
    <View className="flex flex-row items-center justify-center bg-white dark:bg-neutral-900 rounded-lg shadow-sm shadow-neutral-300 dark:shadow-neutral-950/40 mb-3">
      <View className="flex flex-col items-center justify-center p-3">
        {outcome ? (
          <View className="flex flex-row items-center justify-between w-full mb-3">
            <View className={`rounded-full px-3 py-1 ${outcome.chip}`}>
              <Text className={`text-xs font-JakartaBold ${outcome.text}`}>
                {tr(outcome.labelKey)}
              </Text>
            </View>

            {/* Who ended it, and why — the two things a rider looking back at
                a cancelled trip actually wants to know. */}
            {didNotHappen && cancelled_by ? (
              <Text
                className="text-[11px] font-JakartaMedium text-gray-500 dark:text-neutral-400 flex-1 text-right ml-2"
                numberOfLines={1}
              >
                {cancelled_by === "system"
                  ? tr("components.rideCard.cancelledBySystem")
                  : tr(
                      cancelled_by === "driver"
                        ? "components.rideCard.cancelledByDriver"
                        : "components.rideCard.cancelledByYou",
                    )}
                {cancellation_reason
                  ? ` · ${tr(`cancelSheet.reasons.${cancellation_reason}`)}`
                  : ""}
              </Text>
            ) : null}
          </View>
        ) : null}

        <View className="flex flex-row items-center justify-between">
          <Image
            source={{
              uri: `https://maps.geoapify.com/v1/staticmap?style=osm-bright&width=600&height=400&center=lonlat:${destination_longitude},${destination_latitude}&zoom=14&apiKey=${process.env.EXPO_PUBLIC_GEOAPIFY_API_KEY}`,
            }}
            alt={tr("components.rideCard.mapAlt")}
            className="w-[80px] h-[90px] rounded-lg"
          />

          <View className="flex flex-col mx-5 gap-y-5 flex-1">
            <View className="flex flex-row items-center gap-x-2">
              <Image source={icons.to} alt={tr("components.rideCard.originAlt")} className="w-5 h-5" />

              <Text className="font-JakartaMedium text-black dark:text-white" numberOfLines={1}>
                {origin_address}
              </Text>
            </View>

            <View className="flex flex-row items-center gap-x-2">
              <Image
                source={icons.point}
                alt={tr("components.rideCard.destinationAlt")}
                className="w-5 h-5"
              />

              <Text className="font-JakartaMedium text-black dark:text-white" numberOfLines={1}>
                {destination_address}
              </Text>
            </View>
          </View>
        </View>

        <View className="flex flex-col w-full mt-5 bg-general-500 dark:bg-neutral-800 rounded-lg p-3 items-start justify-center">
          <View className="flex flex-row items-center w-full justify-between mb-5">
            <Text className="font-JakartaMedium text-gray-500 dark:text-neutral-400 text-xs">
              {tr("components.rideCard.dateTime")}
            </Text>

            <Text className="font-JakartaMedium text-gray-500 dark:text-neutral-400 text-xs">
              {formatDate(created_at)}, {formatTime(ride_time)}
            </Text>
          </View>

          <View className="flex flex-row items-center w-full justify-between mb-5">
            <Text className="font-JakartaMedium text-gray-500 dark:text-neutral-400 text-xs">
              {tr("components.rideCard.driver")}
            </Text>

            <Text className="font-JakartaMedium text-gray-500 dark:text-neutral-400 text-xs">
              {driverName || tr("components.rideCard.noDriver")}
            </Text>
          </View>

          <View className="flex flex-row items-center w-full justify-between mb-5">
            <Text className="font-JakartaMedium text-gray-500 dark:text-neutral-400 text-xs">
              {tr("components.rideCard.carSeats")}
            </Text>

            <Text className="font-JakartaMedium text-gray-500 dark:text-neutral-400 text-xs">
              {driver.car_seats}
            </Text>
          </View>

          <View className="flex flex-row items-center w-full justify-between mb-5">
            <Text className="font-JakartaMedium text-gray-500 dark:text-neutral-400 text-xs">
              {tr("components.rideCard.fare")}
            </Text>

            <Text className="font-JakartaMedium text-gray-500 dark:text-neutral-400 text-xs">
              ${(ride.fare_price / 100).toFixed(2)}
            </Text>
          </View>

          <View className="flex flex-row items-center w-full justify-between mb-5">
            <Text className="font-JakartaMedium text-gray-500 dark:text-neutral-400 text-xs">
              {tr("components.rideCard.paymentStatus")}
            </Text>

            {/* A ride that never happened has no payment worth reporting as
                successful. A cash ride simply wasn't collected; a card ride
                that was charged before cancellation is called out as owed a
                refund rather than shown as a cheerful green "Paid". */}
            <Text
              className={`font-JakartaMedium capitalize text-xs ${
                didNotHappen
                  ? payment_status === "paid"
                    ? "text-amber-600 dark:text-amber-400"
                    : "text-gray-500 dark:text-neutral-400"
                  : payment_status === "paid" ||
                      payment_status === "cash_collected"
                    ? "text-emerald-500 dark:text-emerald-400"
                    : "text-gray-500 dark:text-neutral-400"
              }`}
            >
              {didNotHappen
                ? payment_status === "paid"
                  ? tr("components.rideCard.paymentRefundDue")
                  : tr("components.rideCard.paymentNotCharged")
                : payment_status === "cash"
                  ? tr("components.rideCard.paymentCash")
                  : payment_status === "cash_collected"
                    ? tr("components.rideCard.paymentCashCollected")
                    : payment_status === "paid"
                      ? tr("components.rideCard.paymentPaid")
                      : tr("components.rideCard.paymentOther", {
                          status: payment_status,
                        })}
            </Text>
          </View>
        </View>
      </View>
    </View>
  );
};
