"use client";

import { Alert, Button, Chip } from "@heroui/react";
import type { CheckoutAddressValidationResult } from "@/lib/checkout/types";

type AddressValidationFeedbackProps = {
  result: CheckoutAddressValidationResult;
  onAcceptRecommended: () => void;
  onKeepOriginal: () => void;
  onEditAddress: () => void;
};

const CONFIDENCE_COLOR: Record<string, "success" | "warning" | "danger"> = {
  high: "success",
  medium: "warning",
  low: "danger",
};

const ADDRESS_TYPE_LABELS: Record<string, string> = {
  residential: "Residential",
  commercial: "Commercial",
  po_box: "PO Box",
  military: "Military",
  unknown: "Unknown",
};

export function AddressValidationFeedback({
  result,
  onAcceptRecommended,
  onKeepOriginal,
  onEditAddress,
}: AddressValidationFeedbackProps) {
  if (result.isValid && !result.recommendedAddress) {
    return <ValidNoCorrections result={result} />;
  }

  if (result.recommendedAddress) {
    return (
      <RecommendedCorrections
        result={result}
        onAcceptRecommended={onAcceptRecommended}
        onKeepOriginal={onKeepOriginal}
      />
    );
  }

  return (
    <InvalidAddress
      result={result}
      onEditAddress={onEditAddress}
      onKeepOriginal={onKeepOriginal}
    />
  );
}

function ValidNoCorrections({ result }: { result: CheckoutAddressValidationResult }) {
  return (
    <div className="flex flex-col gap-4" role="alert">
      <Alert status="success">
        <Alert.Indicator />
        <Alert.Content>
          <Alert.Title>Address verified successfully</Alert.Title>
          <Alert.Description>Your address has been validated and is ready to use.</Alert.Description>
        </Alert.Content>
      </Alert>
      <AddressSummaryCard
        label="Verified address"
        address={result.originalAddress}
        addressType={result.addressType}
      />
    </div>
  );
}

function RecommendedCorrections({
  result,
  onAcceptRecommended,
  onKeepOriginal,
}: {
  result: CheckoutAddressValidationResult;
  onAcceptRecommended: () => void;
  onKeepOriginal: () => void;
}) {
  const rec = result.recommendedAddress!;
  const confidence = rec.confidenceScore;
  const alertStatus = confidence === "high" ? "accent" : "warning";
  const changedSet = new Set(result.changedAttributes);

  return (
    <div className="flex flex-col gap-4">
      <Alert status={alertStatus} role="alert">
        <Alert.Indicator />
        <Alert.Content>
          <Alert.Title>We found a more accurate version of your address</Alert.Title>
          <Alert.Description>{rec.confidenceDescription}</Alert.Description>
        </Alert.Content>
      </Alert>

      <div className="flex items-center gap-2">
        <Chip size="sm" variant="soft" color={CONFIDENCE_COLOR[confidence] ?? "default"}>
          {confidence.charAt(0).toUpperCase() + confidence.slice(1)} confidence
        </Chip>
        {result.addressType !== "unknown" && (
          <Chip size="sm" variant="soft">
            {ADDRESS_TYPE_LABELS[result.addressType] ?? result.addressType}
          </Chip>
        )}
      </div>

      {/* Side-by-side on md+, stacked on mobile */}
      <div
        className="grid grid-cols-1 gap-4 md:grid-cols-2"
        aria-label="Address comparison"
      >
        <AddressSummaryCard
          label="You entered"
          address={result.originalAddress}
        />
        <AddressSummaryCard
          label="Suggested"
          address={{
            addressLine1: rec.addressLine1,
            additionalInformation: rec.additionalInformation,
            city: rec.city,
            postalCode: rec.postalCode,
            country: rec.country,
          }}
          highlightedFields={changedSet}
        />
      </div>

      <div className="flex flex-col gap-2 md:flex-row">
        <Button
          variant="primary"
          className="w-full bg-[#236f6b] font-medium text-white md:w-auto"
          onPress={onAcceptRecommended}
        >
          Use suggested address
        </Button>
        <Button
          variant="ghost"
          className="w-full md:w-auto"
          onPress={onKeepOriginal}
        >
          Keep my address
        </Button>
      </div>
    </div>
  );
}

function InvalidAddress({
  result,
  onEditAddress,
  onKeepOriginal,
}: {
  result: CheckoutAddressValidationResult;
  onEditAddress: () => void;
  onKeepOriginal: () => void;
}) {
  return (
    <div className="flex flex-col gap-4">
      <Alert status="danger" role="alert">
        <Alert.Indicator />
        <Alert.Content>
          <Alert.Title>We couldn&apos;t verify this address</Alert.Title>
          <Alert.Description>Please review the issues below and correct your address.</Alert.Description>
        </Alert.Content>
      </Alert>

      {result.reasons.length > 0 && (
        <ul className="list-inside list-disc space-y-1 text-sm text-default-600">
          {result.reasons.map((reason, i) => (
            <li key={i}>{reason.description}</li>
          ))}
        </ul>
      )}

      <div className="flex flex-col gap-2 md:flex-row">
        <Button
          variant="primary"
          className="w-full bg-[#236f6b] font-medium text-white md:w-auto"
          onPress={onEditAddress}
        >
          Edit address
        </Button>
        <Button
          variant="ghost"
          className="w-full md:w-auto"
          onPress={onKeepOriginal}
        >
          Save anyway
        </Button>
      </div>

      <p className="text-xs text-warning-600">
        Unverified addresses may cause delivery failures or surcharges.
      </p>
    </div>
  );
}

function AddressSummaryCard({
  label,
  address,
  addressType,
  highlightedFields,
}: {
  label: string;
  address: {
    addressLine1: string;
    additionalInformation?: string;
    city: string;
    postalCode: string;
    country: string;
  };
  addressType?: string;
  highlightedFields?: Set<string>;
}) {
  const hl = (field: string, text: string) => {
    if (highlightedFields?.has(field)) {
      return <span className="font-semibold text-[#236f6b]" aria-label={`${field} changed`}>{text}</span>;
    }
    return text;
  };

  return (
    <div className="rounded-lg border border-default-200 p-4">
      <p className="mb-2 text-xs font-semibold uppercase tracking-wide text-default-400">
        {label}
      </p>
      <div className="text-sm text-foreground">
        <p>{hl("address_line_1", address.addressLine1)}</p>
        {address.additionalInformation && (
          <p>{hl("address_line_2", address.additionalInformation)}</p>
        )}
        <p>{hl("city_locality", address.city)}</p>
        <p>{hl("postal_code", address.postalCode)}</p>
        <p>{hl("country_code", address.country)}</p>
      </div>
      {addressType && addressType !== "unknown" && (
        <div className="mt-2">
          <Chip size="sm" variant="soft">
            {ADDRESS_TYPE_LABELS[addressType] ?? addressType}
          </Chip>
        </div>
      )}
    </div>
  );
}
