"use client";

import { useReducer } from "react";
import { useRouter } from "next/navigation";
import { formatDate } from "@/lib/format-date";
import { updateOrder } from "@/actions/orders/update-order";
import { createRefund } from "@/actions/orders/create-refund";
import { useToast } from "./Toast";
import AdminButton from "./design-system/AdminButton";

type Refund = {
  id: string;
  order_id: string;
  amount: number;
  reason: string | null;
  processor: string | null;
  processor_refund_id: string | null;
  status: string;
  created_at: string;
};

type OrderPaymentSectionProps = {
  orderId: string;
  brandId: string | null;
  orderTotal: number;
  payment_processor: string | null;
  payment_status: string | null;
  payment_transaction_id: string | null;
  refunded_amount: number;
  refund_reason: string | null;
  existingRefunds: Refund[];
};

const currencyFormatter = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" });

function formatCurrency(amount: number) {
  return currencyFormatter.format(amount);
}

// --- Reducer state -------------------------------------------------------

type State = {
  processor: string;
  status: string;
  transactionId: string;
  refundAmount: string;
  refundReason: string;
  saving: boolean;
  refunding: boolean;
  error: string | null;
  saved: boolean;
  refundSaved: boolean;
  refundError: string | null;
};

type Action =
  | { type: "SET_PROCESSOR"; value: string }
  | { type: "SET_STATUS"; value: string }
  | { type: "SET_TRANSACTION_ID"; value: string }
  | { type: "SET_REFUND_AMOUNT"; value: string }
  | { type: "SET_REFUND_REASON"; value: string }
  | { type: "SET_SAVING"; value: boolean }
  | { type: "SET_REFUNDING"; value: boolean }
  | { type: "SET_ERROR"; value: string | null }
  | { type: "SET_SAVED"; value: boolean }
  | { type: "SET_REFUND_SAVED"; value: boolean }
  | { type: "SET_REFUND_ERROR"; value: string | null }
  | { type: "RESET_REFUND_FIELDS" };

function reducer(state: State, action: Action): State {
  switch (action.type) {
    case "SET_PROCESSOR":
      return { ...state, processor: action.value };
    case "SET_STATUS":
      return { ...state, status: action.value };
    case "SET_TRANSACTION_ID":
      return { ...state, transactionId: action.value };
    case "SET_REFUND_AMOUNT":
      return { ...state, refundAmount: action.value };
    case "SET_REFUND_REASON":
      return { ...state, refundReason: action.value };
    case "SET_SAVING":
      return { ...state, saving: action.value };
    case "SET_REFUNDING":
      return { ...state, refunding: action.value };
    case "SET_ERROR":
      return { ...state, error: action.value };
    case "SET_SAVED":
      return { ...state, saved: action.value };
    case "SET_REFUND_SAVED":
      return { ...state, refundSaved: action.value };
    case "SET_REFUND_ERROR":
      return { ...state, refundError: action.value };
    case "RESET_REFUND_FIELDS":
      return { ...state, refundAmount: "", refundReason: "", refundSaved: true };
    default:
      return state;
  }
}

function createInitialState(props: OrderPaymentSectionProps): State {
  return {
    processor: props.payment_processor ?? "",
    status: props.payment_status ?? "manual",
    transactionId: props.payment_transaction_id ?? "",
    refundAmount: "",
    refundReason: "",
    saving: false,
    refunding: false,
    error: null,
    saved: false,
    refundSaved: false,
    refundError: null,
  };
}

// --- Subcomponents -------------------------------------------------------

type BalanceSummaryProps = {
  orderTotal: number;
  totalRefunded: number;
  remainingBalance: number;
};

function BalanceSummary({ orderTotal, totalRefunded, remainingBalance }: BalanceSummaryProps) {
  return (
    <div className="rounded-xl border border-stone-200 bg-stone-50 p-4">
      <div className="flex items-center justify-between">
        <div>
          <p className="text-xs font-medium text-stone-500">Order Total</p>
          <p className="text-lg font-bold text-stone-900">{formatCurrency(orderTotal)}</p>
        </div>
        <div className="text-right">
          <p className="text-xs font-medium text-stone-500">Refunded</p>
          <p className="text-lg font-bold text-green-600">{formatCurrency(totalRefunded)}</p>
        </div>
        <div className="text-right">
          <p className="text-xs font-medium text-stone-500">Balance Due</p>
          <p className="text-lg font-bold text-[var(--admin-accent)]">{formatCurrency(remainingBalance)}</p>
        </div>
      </div>
    </div>
  );
}

type PaymentDetailsFormProps = {
  processor: string;
  status: string;
  transactionId: string;
  saving: boolean;
  error: string | null;
  saved: boolean;
  onSubmit: (e: React.FormEvent) => void;
  onChangeProcessor: (value: string) => void;
  onChangeStatus: (value: string) => void;
  onChangeTransactionId: (value: string) => void;
};

function PaymentDetailsForm({
  processor,
  status,
  transactionId,
  saving,
  error,
  saved,
  onSubmit,
  onChangeProcessor,
  onChangeStatus,
  onChangeTransactionId,
}: PaymentDetailsFormProps) {
  return (
    <form onSubmit={onSubmit} className="space-y-4">
      {error && (
        <div className="rounded-xl bg-red-50 border border-red-200 p-4 text-sm text-red-600 flex items-start gap-3">
          <svg className="h-5 w-5 shrink-0 text-red-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
            <path strokeLinecap="round" strokeLinejoin="round" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
          </svg>
          {error}
        </div>
      )}

      {saved && (
        <div className="rounded-xl bg-green-50 border border-green-200 p-4 text-sm text-green-700 flex items-center gap-3">
          <svg className="h-5 w-5 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
            <path strokeLinecap="round" strokeLinejoin="round" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
          </svg>
          Payment details saved
        </div>
      )}

      <div className="grid grid-cols-2 gap-4">
        <div>
          <label htmlFor="fld-1-processor"  className="mb-1 block text-xs font-semibold text-stone-500">Processor</label>
          <select id="fld-1-processor"  aria-label="Select"
            value={processor}
            onChange={(e) => onChangeProcessor(e.target.value)}
            className="w-full rounded-xl border border-stone-200 bg-white px-3 py-2.5 text-sm outline-none focus:border-[var(--admin-accent)] focus:ring-2 focus:ring-[var(--admin-accent)]/20"
          >
            <option value="">— None —</option>
            {["manual", "stripe", "square", "cash", "venmo", "other"].map((p) => (
              <option key={p} value={p}>
                {p.charAt(0).toUpperCase() + p.slice(1)}
              </option>
            ))}
          </select>
        </div>

        <div>
          <label htmlFor="fld-2-payment-status"  className="mb-1 block text-xs font-semibold text-stone-500">Payment Status</label>
          <select id="fld-2-payment-status"  aria-label="Select"
            value={status}
            onChange={(e) => onChangeStatus(e.target.value)}
            className="w-full rounded-xl border border-stone-200 bg-white px-3 py-2.5 text-sm outline-none focus:border-[var(--admin-accent)] focus:ring-2 focus:ring-[var(--admin-accent)]/20"
          >
            {["pending", "paid", "failed", "refunded", "cancelled"].map((s) => (
              <option key={s} value={s}>
                {s.charAt(0).toUpperCase() + s.slice(1)}
              </option>
            ))}
          </select>
        </div>
      </div>

      <div>
        <label htmlFor="fld-3-transaction-id"  className="mb-1 block text-xs font-semibold text-stone-500">Transaction ID</label>
        <input id="fld-3-transaction-id"  aria-label="External Payment Reference"
          type="text"
          value={transactionId}
          onChange={(e) => onChangeTransactionId(e.target.value)}
          placeholder="External payment reference"
          className="w-full rounded-xl border border-stone-200 bg-white px-4 py-2.5 text-sm outline-none focus:border-[var(--admin-accent)] focus:ring-2 focus:ring-[var(--admin-accent)]/20"
        />
      </div>

      <AdminButton
        type="submit"
        disabled={saving}
        isLoading={saving}
        variant="primary"
      >
        {saving ? "Saving..." : "Save Payment Details"}
      </AdminButton>
    </form>
  );
}

type RefundHistoryProps = {
  refunds: Refund[];
};

function RefundHistory({ refunds }: RefundHistoryProps) {
  if (refunds.length === 0) return null;
  return (
    <div>
      <p className="mb-3 text-sm font-semibold text-stone-700">
        Refund History ({refunds.length})
      </p>
      <div className="space-y-2">
        {refunds.map((r) => (
          <div
            key={r.id}
            className="flex items-center justify-between rounded-xl border border-stone-200 bg-white px-4 py-3"
          >
            <div>
              <p className="font-semibold text-stone-900">
                {formatCurrency(Number(r.amount))}
              </p>
              {r.reason && (
                <p className="text-xs text-stone-500">{r.reason}</p>
              )}
              <p className="text-xs text-stone-400">
                {formatDate(r.created_at)}
              </p>
            </div>
            <span
              className={`rounded-full px-2.5 py-0.5 text-xs font-bold ${
                r.status === "completed"
                  ? "bg-green-50 text-green-700 border border-green-200"
                  : "bg-stone-100 text-stone-500 border border-stone-200"
              }`}
            >
              {r.status}
            </span>
          </div>
        ))}
      </div>
    </div>
  );
}

type RecordRefundFormProps = {
  refundAmount: string;
  refundReason: string;
  refundError: string | null;
  refundSaved: boolean;
  refunding: boolean;
  remainingBalance: number;
  onSubmit: (e: React.FormEvent) => void;
  onChangeRefundAmount: (value: string) => void;
  onChangeRefundReason: (value: string) => void;
};

function RecordRefundForm({
  refundAmount,
  refundReason,
  refundError,
  refundSaved,
  refunding,
  remainingBalance,
  onSubmit,
  onChangeRefundAmount,
  onChangeRefundReason,
}: RecordRefundFormProps) {
  return (
    <div className="rounded-xl border border-dashed border-stone-300 bg-stone-50 p-4">
      <p className="mb-3 text-sm font-semibold text-stone-700">Record a Refund</p>
      {refundSaved && (
        <div className="mb-3 rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 flex items-center gap-2">
          <svg className="h-4 w-4 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
            <path strokeLinecap="round" strokeLinejoin="round" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
          </svg>
          Refund recorded successfully
        </div>
      )}
      <form onSubmit={onSubmit} className="space-y-3">
        <div>
          <label className="mb-1 block text-xs font-semibold text-stone-500" htmlFor="fld-amount">Amount</label>
          <div className="relative">
            <span className="absolute left-3 top-1/2 -translate-y-1/2 text-stone-400 text-sm">$</span>
            <input id="fld-amount" aria-label="Number"
              type="number"
              step="0.01"
              min="0.01"
              max={remainingBalance}
              value={refundAmount}
              onChange={(e) => onChangeRefundAmount(e.target.value)}
              placeholder={`Max ${formatCurrency(remainingBalance)}`}
              className={`w-full rounded-xl border bg-white pl-8 pr-4 py-2.5 text-sm outline-none focus:ring-2 focus:ring-[var(--admin-accent)]/20 ${
                refundError
                  ? "border-red-400 bg-red-50"
                  : "border-stone-200 focus:border-[var(--admin-accent)]"
              }`}
            />
          </div>
          {refundError && (
            <p className="mt-1 text-xs text-red-500">{refundError}</p>
          )}
        </div>
        <div>
          <label htmlFor="fld-4-reason"  className="mb-1 block text-xs font-semibold text-stone-500">Reason</label>
          <input id="fld-4-reason"  aria-label="Customer Request, Defective Product, Etc."
            type="text"
            value={refundReason}
            onChange={(e) => onChangeRefundReason(e.target.value)}
            placeholder="Customer request, defective product, etc."
            className="w-full rounded-xl border border-stone-200 bg-white px-4 py-2.5 text-sm outline-none focus:border-[var(--admin-accent)] focus:ring-2 focus:ring-[var(--admin-accent)]/20"
          />
        </div>
        <AdminButton
          type="submit"
          disabled={!refundAmount || Number(refundAmount) <= 0 || refunding}
          isLoading={refunding}
          variant="danger"
          fullWidth
        >
          {refunding ? "Processing..." : `Record Refund (Max ${formatCurrency(remainingBalance)})`}
        </AdminButton>
      </form>
    </div>
  );
}

// --- Main component ------------------------------------------------------

export default function OrderPaymentSection(props: OrderPaymentSectionProps) {
  const {
    orderId,
    brandId,
    orderTotal,
    existingRefunds,
  } = props;
  const router = useRouter();
  const { success: showSuccess, error: showError } = useToast();
  const [state, dispatch] = useReducer(reducer, createInitialState(props));

  const totalRefunded = existingRefunds
    .filter((r) => r.status === "completed")
    .reduce((sum, r) => sum + Number(r.amount), 0);
  const remainingBalance = Math.max(0, orderTotal - totalRefunded);

  // Validation for refund
  function validateRefund(): boolean {
    const amount = Number(state.refundAmount);
    if (!amount || amount <= 0) {
      dispatch({ type: "SET_REFUND_ERROR", value: "Please enter a valid refund amount" });
      return false;
    }
    if (amount > remainingBalance) {
      dispatch({
        type: "SET_REFUND_ERROR",
        value: `Amount cannot exceed remaining balance of ${formatCurrency(remainingBalance)}`,
      });
      return false;
    }
    dispatch({ type: "SET_REFUND_ERROR", value: null });
    return true;
  }

  async function handleSavePayment(e: React.FormEvent) {
    e.preventDefault();
    dispatch({ type: "SET_SAVING", value: true });
    dispatch({ type: "SET_ERROR", value: null });
    dispatch({ type: "SET_SAVED", value: false });

    const result = await updateOrder(orderId, brandId, {
      payment_processor: state.processor || null,
      payment_status: state.status,
      payment_transaction_id: state.transactionId || null,
    });

    if (!result.success) {
      showError("Failed to save", result.error ?? "Please try again");
      dispatch({ type: "SET_ERROR", value: result.error ?? "Failed to save" });
    } else {
      showSuccess("Payment saved", "Payment details have been updated");
      dispatch({ type: "SET_SAVED", value: true });
    }
    dispatch({ type: "SET_SAVING", value: false });
  }

  async function handleRefund(e: React.FormEvent) {
    e.preventDefault();
    if (!validateRefund()) return;

    const amount = Number(state.refundAmount);

    dispatch({ type: "SET_REFUNDING", value: true });
    dispatch({ type: "SET_ERROR", value: null });
    dispatch({ type: "SET_REFUND_SAVED", value: false });

    const result = await createRefund(orderId, brandId, {
      amount,
      reason: state.refundReason || null,
    });

    if (!result.success) {
      showError("Failed to record refund", result.error ?? "Please try again");
      dispatch({ type: "SET_ERROR", value: result.error ?? "Failed to record refund" });
    } else {
      showSuccess("Refund recorded", `${formatCurrency(amount)} has been refunded`);
      dispatch({ type: "RESET_REFUND_FIELDS" });
      router.refresh();
    }
    dispatch({ type: "SET_REFUNDING", value: false });
  }

  return (
    <div className="space-y-5">
      <BalanceSummary
        orderTotal={orderTotal}
        totalRefunded={totalRefunded}
        remainingBalance={remainingBalance}
      />

      <PaymentDetailsForm
        processor={state.processor}
        status={state.status}
        transactionId={state.transactionId}
        saving={state.saving}
        error={state.error}
        saved={state.saved}
        onSubmit={handleSavePayment}
        onChangeProcessor={(v) => dispatch({ type: "SET_PROCESSOR", value: v })}
        onChangeStatus={(v) => dispatch({ type: "SET_STATUS", value: v })}
        onChangeTransactionId={(v) => dispatch({ type: "SET_TRANSACTION_ID", value: v })}
      />

      <RefundHistory refunds={existingRefunds} />

      {remainingBalance > 0 && (
        <RecordRefundForm
          refundAmount={state.refundAmount}
          refundReason={state.refundReason}
          refundError={state.refundError}
          refundSaved={state.refundSaved}
          refunding={state.refunding}
          remainingBalance={remainingBalance}
          onSubmit={handleRefund}
          onChangeRefundAmount={(v) => {
            dispatch({ type: "SET_REFUND_AMOUNT", value: v });
            dispatch({ type: "SET_REFUND_ERROR", value: null });
          }}
          onChangeRefundReason={(v) => dispatch({ type: "SET_REFUND_REASON", value: v })}
        />
      )}
    </div>
  );
}