import {
  Alert,
  Button,
  Group,
  Modal,
  Stack,
  Text,
  TextInput,
} from "@mantine/core";
import { useMutation, useQuery } from "@tanstack/react-query";
import { AlertCircle, Send, XCircle } from "lucide-react";
import { useState } from "react";
import { useNavigate } from "react-router-dom";

import { api } from "@/services/api";
import type { Freight } from "@edr/types";

import { PriceChangeModal } from "@/pages/bookings/resubmit/PriceChangeModal";
import { ResubmitDocuments } from "@/pages/bookings/resubmit/ResubmitDocuments";
import { useResubmitFlow } from "@/pages/bookings/resubmit/useResubmitFlow";

import { CardTitle, PageShell, SectionCard } from "./components/layout";
import { BodyGrid } from "./components/layout";
import { CompanyInfoCard } from "./components/CompanyInfoCard";
import { ContainersCard } from "./components/ContainersCard";
import { ContractInfoCard } from "./components/ContractInfoCard";
import { ActionRequiredBanner, MutationErrors } from "./components/Notices";
import { PageHeader } from "./components/PageHeader";
import { EstimateCard } from "./components/pricing";
import { ScheduleCard } from "./components/ScheduleCard";
import { ShipmentDetailsCard } from "./components/ShipmentDetailsCard";
import { StatusHero } from "./components/StatusHero";
import { SupportCard } from "./components/SupportCard";

/**
 * Detail-page view for a booking staff returned with CHANGES_REQUESTED.
 *
 * Unlike a fresh draft, this booking already went through submission, so the
 * documents shown are exactly the files the customer submitted (`booking.files`)
 * — not a fixed required-document list. The customer reviews the staff note,
 * replaces any document they need to update, and resubmits in place.
 */
export function ChangesRequestedView({
  booking,
  onBookingUpdated,
}: {
  booking: Freight.IBooking;
  onBookingUpdated: () => void;
}) {
  const navigate = useNavigate();
  const flow = useResubmitFlow(booking, { onResubmitted: onBookingUpdated });

  const [cancelDialogOpen, setCancelDialogOpen] = useState(false);
  const [cancelReason, setCancelReason] = useState("");

  const { data: generatedPricing } = useQuery(
    api.bookings.generatePrice.queryOptions({
      input: { id: booking.id },
      enabled: !booking.pricingBreakdown,
    }),
  );
  const pricing = (booking.pricingBreakdown ??
    generatedPricing ??
    null) as Freight.PricingBreakdown | null;

  const cancelMutation = useMutation({
    mutationFn: (reason: string) =>
      api.bookings.cancel.call({ id: booking.id, reason }),
    onSuccess: () => {
      setCancelDialogOpen(false);
      onBookingUpdated();
    },
  });

  return (
    <PageShell>
      <PageHeader
        booking={booking}
        menuActions={{
          onCancel: () => setCancelDialogOpen(true),
          onSupport: () => navigate("/support"),
        }}
      />

      <MutationErrors mutations={[...flow.mutations, cancelMutation]} />

      <StatusHero booking={booking}>
        {booking.latestChangeRequestNote ? (
          <ActionRequiredBanner title="Review the requested changes, then resubmit.">
            {booking.latestChangeRequestNote}
          </ActionRequiredBanner>
        ) : undefined}
      </StatusHero>

      <BodyGrid
        left={
          <>
            <ShipmentDetailsCard booking={booking} />

            <ContainersCard booking={booking} />

            <ContractInfoCard booking={booking} />

            <SectionCard>
              <Group justify="space-between" align="center" mb="md">
                <CardTitle>Your documents</CardTitle>
              </Group>
              <Text fz="12.5px" c="#6B7C8E" mb="sm">
                Update the documents for this booking, then resubmit for review.
                Replace any that changed and attach any that are still required.
              </Text>

              <ResubmitDocuments flow={flow} />

              {flow.validationError && (
                <Alert
                  color="red"
                  radius="md"
                  icon={<AlertCircle size={16} />}
                  mt="md"
                >
                  {flow.validationError}
                </Alert>
              )}

              <Button
                fullWidth
                mt="lg"
                radius={10}
                color="#0C1A2B"
                leftSection={<Send size={16} />}
                onClick={flow.resubmit}
                loading={flow.isBusy}
                disabled={flow.isBusy}
                styles={{
                  root: { height: 46 },
                  label: { fontSize: 14, fontWeight: 800 },
                }}
              >
                {flow.isBusy ? "Resubmitting…" : "Resubmit for review"}
              </Button>
            </SectionCard>
          </>
        }
        right={
          <>
            <EstimateCard
              pricing={pricing}
              title="Estimated Cost"
              chip="Not invoiced"
            />
            <ScheduleCard booking={booking} title="Schedule & Service" />
            <CompanyInfoCard booking={booking} />
            <SupportCard onCancel={() => setCancelDialogOpen(true)} />
          </>
        }
      />

      <PriceChangeModal
        data={flow.priceChange}
        onClose={flow.clearPriceChange}
        onConfirm={flow.confirmSubmit}
        confirmPending={flow.confirmSubmitPending}
      />

      <Modal
        opened={cancelDialogOpen}
        onClose={() => setCancelDialogOpen(false)}
        title={<Text fw={700}>Cancel booking</Text>}
        radius="lg"
        centered
      >
        <Stack gap="md">
          <Text size="sm" c="dimmed">
            Are you sure you want to cancel <strong>{booking.reference}</strong>?
            This action cannot be undone.
          </Text>
          <TextInput
            label="Reason for cancellation (optional)"
            placeholder="e.g. Change of plans, duplicate booking…"
            value={cancelReason}
            onChange={(e) => setCancelReason(e.currentTarget.value)}
            radius="md"
            data-autofocus
          />
          <Group justify="flex-end" gap="sm">
            <Button
              variant="default"
              radius="md"
              onClick={() => setCancelDialogOpen(false)}
            >
              Keep booking
            </Button>
            <Button
              color="red"
              radius="md"
              onClick={() =>
                cancelMutation.mutate(cancelReason.trim() || "Cancelled by customer")
              }
              disabled={cancelMutation.isPending}
              loading={cancelMutation.isPending}
              leftSection={
                !cancelMutation.isPending ? <XCircle size={15} /> : undefined
              }
            >
              Yes, cancel
            </Button>
          </Group>
        </Stack>
      </Modal>
    </PageShell>
  );
}
