import { useMemo } from "react";
import { useQuery } from "@tanstack/react-query";
import { useNavigate } from "react-router-dom";
import {
  Box,
  Button,
  Divider,
  Loader,
  Stack,
  Text,
  ThemeIcon,
} from "@mantine/core";
import { AlertTriangle, CheckCircle2, FileSearch, FileText, Home, RotateCcw } from "lucide-react";
import { api } from "@/services/api";

function extractOrderId(): string | null {
  const params = new URLSearchParams(window.location.search);
  const fromQuery = params.get("merch_order_id");
  if (fromQuery) return fromQuery;
  const segments = window.location.pathname.split("/").filter(Boolean);
  return segments[segments.length - 1] ?? null;
}

function PaymentCard({ children }: { children: React.ReactNode }) {
  return (
    <Box
      style={{
        minHeight: "100dvh",
        background: "#f8fafc",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        padding: "24px",
      }}
    >
      <Box
        style={{
          width: "100%",
          maxWidth: 460,
          background: "#fff",
          borderRadius: 24,
          border: "1.5px solid #e5e7eb",
          boxShadow: "0 4px 24px 0 rgba(0,0,0,0.07)",
          overflow: "hidden",
        }}
      >
        {children}
      </Box>
    </Box>
  );
}

export default function CheckPaymentPage() {
  const navigate = useNavigate();
  const orderId = useMemo(() => extractOrderId(), []);

  const { data, isLoading, isError, error } = useQuery(
    api.bookings.checkPayment.queryOptions({
      input: { orderId: orderId! },
      enabled: !!orderId,
      retry: false,
    }),
  );

  const isSuccess = data?.status === "PAY_SUCCESS";

  if (!orderId) {
    return (
      <PaymentCard>
        <Box
          style={{
            background: "linear-gradient(135deg, #f97316 0%, #fb923c 100%)",
            padding: "40px 32px 32px",
            textAlign: "center",
          }}
        >
          <ThemeIcon
            size={80}
            radius="xl"
            style={{
              background: "rgba(255,255,255,0.18)",
              border: "2px solid rgba(255,255,255,0.3)",
              margin: "0 auto 20px",
              display: "flex",
            }}
          >
            <FileSearch size={42} color="#fff" />
          </ThemeIcon>
          <Text fw={800} fz={24} c="#fff" lh={1.2}>
            No payment reference
          </Text>
          <Text fz={14} c="rgba(255,255,255,0.82)" mt={8}>
            We could not find a payment order to verify.
          </Text>
        </Box>
        <Stack gap={10} p={32}>
          <Button
            fullWidth
            size="md"
            radius={12}
            color="orange"
            onClick={() => navigate("/bookings")}
            styles={{ root: { height: 48, fontWeight: 700 } }}
          >
            Back to my bookings
          </Button>
        </Stack>
      </PaymentCard>
    );
  }

  if (isLoading) {
    return (
      <PaymentCard>
        <Box style={{ padding: "64px 32px", textAlign: "center" }}>
          <Loader size={48} color="edr-green" type="dots" mx="auto" mb={24} />
          <Text fw={700} fz={18} c="#10202F">
            Verifying your payment…
          </Text>
          <Text fz={14} c="dimmed" mt={8}>
            Please wait, this usually takes a few seconds.
          </Text>
        </Box>
      </PaymentCard>
    );
  }

  if (isSuccess) {
    return (
      <PaymentCard>
        <Box
          style={{
            background: "linear-gradient(135deg, #059669 0%, #0ea371 100%)",
            padding: "40px 32px 32px",
            textAlign: "center",
          }}
        >
          <ThemeIcon
            size={80}
            radius="xl"
            style={{
              background: "rgba(255,255,255,0.2)",
              border: "2px solid rgba(255,255,255,0.35)",
              margin: "0 auto 20px",
              display: "flex",
            }}
          >
            <CheckCircle2 size={42} color="#fff" strokeWidth={2} />
          </ThemeIcon>
          <Text fw={800} fz={24} c="#fff" lh={1.2}>
            Payment verified
          </Text>
          <Text fz={14} c="rgba(255,255,255,0.82)" mt={8} lh={1.5}>
            Your booking is confirmed and payment is complete.
          </Text>
        </Box>

        <Stack gap={0} p={32}>
          <Box
            style={{
              background: "#f0fdf4",
              border: "1px solid #bbf7d0",
              borderRadius: 14,
              padding: "14px 18px",
            }}
          >
            <Text fz={13.5} c="#14532d" lh={1.5} ta="center">
              EDR staff will assign a train and you will be notified of any updates.
            </Text>
          </Box>
          <Divider my={24} color="#e5e7eb" />
          <Stack gap={10}>
            <Button
              fullWidth
              size="md"
              radius={12}
              color="edr-green"
              leftSection={<FileText size={17} />}
              onClick={() => navigate("/bookings")}
              styles={{ root: { height: 48, fontWeight: 700, fontSize: 15 } }}
            >
              Go to my bookings
            </Button>
            <Button
              fullWidth
              size="md"
              radius={12}
              variant="subtle"
              color="gray"
              leftSection={<Home size={17} />}
              onClick={() => navigate("/")}
              styles={{ root: { height: 44, fontWeight: 600, fontSize: 14 } }}
            >
              Back to home
            </Button>
          </Stack>
          <Text fz={12} c="dimmed" ta="center" mt={20}>
            Questions?{" "}
            <Text span c="edr-green" fw={600}>
              support@edr.et
            </Text>
          </Text>
        </Stack>
      </PaymentCard>
    );
  }

  if (isError) {
    return (
      <PaymentCard>
        <Box
          style={{
            background: "linear-gradient(135deg, #dc2626 0%, #ef4444 100%)",
            padding: "40px 32px 32px",
            textAlign: "center",
          }}
        >
          <ThemeIcon
            size={80}
            radius="xl"
            style={{
              background: "rgba(255,255,255,0.18)",
              border: "2px solid rgba(255,255,255,0.3)",
              margin: "0 auto 20px",
              display: "flex",
            }}
          >
            <AlertTriangle size={42} color="#fff" strokeWidth={2} />
          </ThemeIcon>
          <Text fw={800} fz={24} c="#fff" lh={1.2}>
            Verification failed
          </Text>
          <Text fz={14} c="rgba(255,255,255,0.82)" mt={8} lh={1.5}>
            We could not verify your payment status.
          </Text>
        </Box>

        <Stack gap={0} p={32}>
          <Box
            style={{
              background: "#fff7f7",
              border: "1px solid #fecaca",
              borderRadius: 14,
              padding: "14px 18px",
            }}
          >
            <Text fz={13.5} c="#7f1d1d" ta="center" lh={1.5}>
              {error instanceof Error
                ? error.message
                : "An unexpected error occurred. Please try again or contact support."}
            </Text>
          </Box>
          <Divider my={24} color="#e5e7eb" />
          <Stack gap={10}>
            <Button
              fullWidth
              size="md"
              radius={12}
              color="red"
              leftSection={<RotateCcw size={17} />}
              onClick={() => navigate("/bookings")}
              styles={{ root: { height: 48, fontWeight: 700, fontSize: 15 } }}
            >
              Back to my bookings
            </Button>
            <Button
              fullWidth
              size="md"
              radius={12}
              variant="subtle"
              color="gray"
              leftSection={<Home size={17} />}
              onClick={() => navigate("/")}
              styles={{ root: { height: 44, fontWeight: 600, fontSize: 14 } }}
            >
              Back to home
            </Button>
          </Stack>
          <Text fz={12} c="dimmed" ta="center" mt={20}>
            Need help?{" "}
            <Text span c="red.6" fw={600}>
              support@edr.et
            </Text>
          </Text>
        </Stack>
      </PaymentCard>
    );
  }

  // Non-success status (e.g. PAY_FAIL, PENDING, etc.)
  return (
    <PaymentCard>
      <Box
        style={{
          background: "linear-gradient(135deg, #d97706 0%, #f59e0b 100%)",
          padding: "40px 32px 32px",
          textAlign: "center",
        }}
      >
        <ThemeIcon
          size={80}
          radius="xl"
          style={{
            background: "rgba(255,255,255,0.18)",
            border: "2px solid rgba(255,255,255,0.3)",
            margin: "0 auto 20px",
            display: "flex",
          }}
        >
          <AlertTriangle size={42} color="#fff" strokeWidth={2} />
        </ThemeIcon>
        <Text fw={800} fz={24} c="#fff" lh={1.2}>
          Payment incomplete
        </Text>
        <Text fz={14} c="rgba(255,255,255,0.82)" mt={8} lh={1.5}>
          Status:{" "}
          <Text span fw={700}>
            {data?.status ?? "Unknown"}
          </Text>
        </Text>
      </Box>

      <Stack gap={0} p={32}>
        <Box
          style={{
            background: "#fffbeb",
            border: "1px solid #fde68a",
            borderRadius: 14,
            padding: "14px 18px",
          }}
        >
          <Text fz={13.5} c="#78350f" ta="center" lh={1.5}>
            Your payment did not complete successfully. Nothing has been charged.
            You can retry from your booking page.
          </Text>
        </Box>
        <Divider my={24} color="#e5e7eb" />
        <Stack gap={10}>
          <Button
            fullWidth
            size="md"
            radius={12}
            color="orange"
            leftSection={<RotateCcw size={17} />}
            onClick={() => navigate("/bookings")}
            styles={{ root: { height: 48, fontWeight: 700, fontSize: 15 } }}
          >
            Back to my bookings — retry payment
          </Button>
          <Button
            fullWidth
            size="md"
            radius={12}
            variant="subtle"
            color="gray"
            leftSection={<Home size={17} />}
            onClick={() => navigate("/")}
            styles={{ root: { height: 44, fontWeight: 600, fontSize: 14 } }}
          >
            Back to home
          </Button>
        </Stack>
        <Text fz={12} c="dimmed" ta="center" mt={20}>
          Need help?{" "}
          <Text span c="orange.7" fw={600}>
            support@edr.et
          </Text>
        </Text>
      </Stack>
    </PaymentCard>
  );
}
