"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { CheckCircleIcon, ClockIcon, WifiIcon } from "@heroicons/react/24/outline";
import { Button } from "@/components/atoms/button";
import { AlertBanner } from "@/components/molecules/AlertBanner/AlertBanner";
import { SubCard } from "@/components/molecules/SubCard/SubCard";
import { ServicesBackLink } from "@/features/services/components/base/ServicesBackLink";
import { AddressConfirmation } from "@/features/services/components";
import {
  useAccountInternetPlan,
  useInternetEligibility,
  useRequestInternetEligibilityCheck,
  useServicesBasePath,
} from "@/features/services/hooks";
import { CardPricing } from "@/features/services/components/base/CardPricing";
import type { Address } from "@customer-portal/domain/customer";
import type { InternetPlanCatalogItem } from "@customer-portal/domain/services";
import { ORDER_TYPE } from "@customer-portal/domain/orders";

const LOCKED_STATUS_CONFIG: Record<
  string,
  {
    variant: "info" | "success" | "warning";
    title: string;
    message: string;
    buttonLabel: string;
    buttonHref?: string;
  }
> = {
  pending: {
    variant: "info",
    title: "Availability review already in progress",
    message: "We're already verifying your address. You'll receive an update when it's complete.",
    buttonLabel: "View status",
  },
  eligible: {
    variant: "success",
    title: "You're already eligible",
    message: "Your address is eligible. You can select a plan and continue.",
    buttonLabel: "View plans",
  },
  ineligible: {
    variant: "warning",
    title: "Service not available",
    message: "Our team determined service isn't available at your address.",
    buttonLabel: "Contact support",
    buttonHref: "/account/support/new",
  },
};

function LockedStatusView({
  status,
  servicesBasePath,
}: {
  status: string;
  servicesBasePath: string;
}) {
  const config = LOCKED_STATUS_CONFIG[status];
  if (!config) return null;
  const href = config.buttonHref ?? `${servicesBasePath}/internet`;
  return (
    <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 pb-20 pt-8">
      <ServicesBackLink href={`${servicesBasePath}/internet`} label="Back to Internet" />
      <div className="mt-8">
        <AlertBanner variant={config.variant} title={config.title} elevated>
          <div className="flex flex-col sm:flex-row sm:items-center gap-3">
            <span className="text-sm text-foreground/80">{config.message}</span>
            <Button as="a" href={href} size="sm" className="sm:ml-auto">
              {config.buttonLabel}
            </Button>
          </div>
        </AlertBanner>
      </div>
    </div>
  );
}

function SelectedPlanPreviewContent({
  planLoading,
  plan,
}: {
  planLoading: boolean;
  plan?: InternetPlanCatalogItem | undefined;
}) {
  if (planLoading)
    return <div className="text-sm text-muted-foreground">Loading selected plan…</div>;
  if (!plan) return null;
  return (
    <div className="flex items-center justify-between gap-3 flex-wrap">
      <div>
        <p className="text-xs text-muted-foreground">Selected plan</p>
        <h3 className="text-sm font-semibold text-foreground">{plan.name}</h3>
      </div>
      <CardPricing monthlyPrice={plan.monthlyPrice} size="sm" alignment="right" />
    </div>
  );
}

function SelectedPlanPreview({
  planLoading,
  plan,
}: {
  planLoading: boolean;
  plan?: InternetPlanCatalogItem | undefined;
}) {
  return (
    <div className="mb-6 bg-card border border-border rounded-xl p-4 shadow-[var(--cp-shadow-1)]">
      <div className="flex items-center gap-3">
        <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-primary/10 border border-primary/20 flex-shrink-0">
          <WifiIcon className="h-5 w-5 text-primary" />
        </div>
        <div className="flex-1 min-w-0">
          <SelectedPlanPreviewContent planLoading={planLoading} plan={plan} />
        </div>
      </div>
    </div>
  );
}

function SubmitRequestCard({
  autoEligibilityRequest,
  submissionError,
  submitDisabled,
  isPending,
  onSubmit,
}: {
  autoEligibilityRequest: boolean;
  submissionError: string | null;
  submitDisabled: boolean;
  isPending: boolean;
  onSubmit: () => void;
}) {
  return (
    <SubCard
      title="Submit Request"
      icon={<CheckCircleIcon className="h-5 w-5" />}
      footer={
        <div className="flex flex-col sm:flex-row gap-3">
          <Button
            type="button"
            onClick={onSubmit}
            disabled={submitDisabled}
            isLoading={isPending}
            loadingText="Submitting..."
            className="w-full sm:w-auto"
          >
            Request availability
          </Button>
        </div>
      }
    >
      <div className="space-y-3">
        <div className="flex items-center gap-2 text-sm text-muted-foreground">
          <ClockIcon className="h-4 w-4 text-info" />
          <span>Manual verification typically takes 1-2 business days.</span>
        </div>
        {autoEligibilityRequest && (
          <div className="text-xs text-info">
            This request will submit automatically after you confirm your address.
          </div>
        )}
      </div>
      {submissionError && (
        <AlertBanner variant="error" title="Request failed" className="mt-4">
          {submissionError}
        </AlertBanner>
      )}
    </SubCard>
  );
}

function EligibilityRequestHeader() {
  return (
    <div className="mt-6 mb-8 text-center">
      <div className="flex justify-center mb-4">
        <div className="flex h-14 w-14 items-center justify-center rounded-2xl bg-gradient-to-br from-primary/20 to-primary/5 border border-primary/20">
          <WifiIcon className="h-7 w-7 text-primary" />
        </div>
      </div>
      <h1 className="text-2xl md:text-3xl font-bold text-foreground mb-2">
        Request Availability Check
      </h1>
      <p className="text-muted-foreground max-w-md mx-auto text-sm">
        Confirm your installation address and we&apos;ll verify service availability.
      </p>
    </div>
  );
}

function EligibilityStatusAlerts({
  isLoading,
  isError,
  onRetry,
}: {
  isLoading: boolean;
  isError: boolean;
  onRetry: () => void;
}) {
  return (
    <>
      {isLoading && (
        <AlertBanner variant="info" title="Checking availability status" elevated>
          We&apos;re loading your latest eligibility status.
        </AlertBanner>
      )}
      {isError && (
        <AlertBanner variant="warning" title="Unable to check eligibility status" elevated>
          <div className="flex flex-col sm:flex-row sm:items-center gap-3">
            <span className="text-sm text-foreground/80">
              Please try again or continue if you need to submit a new request.
            </span>
            <Button type="button" size="sm" className="sm:ml-auto" onClick={onRetry}>
              Try again
            </Button>
          </div>
        </AlertBanner>
      )}
    </>
  );
}

export function InternetEligibilityRequestView() {
  const router = useRouter();
  const servicesBasePath = useServicesBasePath();
  const searchParams = useSearchParams();
  const autoEligibilityRequest = searchParams?.get("autoEligibilityRequest") === "1";
  const planSku = searchParams?.get("planSku")?.trim() || undefined;

  const { plan, isLoading: planLoading } = useAccountInternetPlan(planSku);
  const eligibilityQuery = useInternetEligibility();
  const eligibilityRequest = useRequestInternetEligibilityCheck();

  const [addressConfirmed, setAddressConfirmed] = useState(false);
  const [address, setAddress] = useState<Address | undefined>();
  const [submissionError, setSubmissionError] = useState<string | null>(null);
  const [autoSubmitted, setAutoSubmitted] = useState(false);

  const eligibilityStatus = eligibilityQuery.data?.status;
  const isRequestLocked =
    eligibilityStatus === "pending" ||
    eligibilityStatus === "eligible" ||
    eligibilityStatus === "ineligible";

  const requestNotes = useMemo(() => {
    if (!autoEligibilityRequest && !planSku) return;
    const notes: string[] = [];
    if (autoEligibilityRequest) notes.push("Auto availability request after signup.");
    if (planSku) notes.push(`Selected plan SKU: ${planSku}`);
    return notes.join(" ");
  }, [autoEligibilityRequest, planSku]);

  const handleAddressConfirmed = (confirmedAddress?: Address) => {
    setAddressConfirmed(true);
    setAddress(confirmedAddress);
    setSubmissionError(null);
  };

  const handleAddressIncomplete = () => {
    setAddressConfirmed(false);
    setAddress(undefined);
  };

  const handleSubmit = useCallback(async () => {
    if (isRequestLocked) {
      setSubmissionError("An availability request already exists for this account.");
      return;
    }
    if (!addressConfirmed || !address) {
      setSubmissionError("Confirm your installation address to continue.");
      return;
    }
    try {
      setSubmissionError(null);
      const response = await eligibilityRequest.mutateAsync({
        address,
        ...(requestNotes !== undefined && { notes: requestNotes }),
      });
      router.push(
        `${servicesBasePath}/internet/request-submitted?requestId=${encodeURIComponent(response.requestId)}`
      );
    } catch (error) {
      setSubmissionError(
        error instanceof Error ? error.message : "Failed to request availability check."
      );
    }
  }, [
    address,
    addressConfirmed,
    eligibilityRequest,
    isRequestLocked,
    requestNotes,
    router,
    servicesBasePath,
  ]);

  useEffect(() => {
    if (!autoEligibilityRequest || autoSubmitted) return;
    if (!addressConfirmed || !address) return;
    if (isRequestLocked) return;
    setAutoSubmitted(true);
    void handleSubmit();
  }, [
    address,
    addressConfirmed,
    autoEligibilityRequest,
    autoSubmitted,
    handleSubmit,
    isRequestLocked,
  ]);

  if (isRequestLocked && eligibilityStatus) {
    return <LockedStatusView status={eligibilityStatus} servicesBasePath={servicesBasePath} />;
  }

  return (
    <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 pb-20 pt-8">
      <ServicesBackLink href={`${servicesBasePath}/internet`} label="Back to Internet" />
      <EligibilityRequestHeader />
      {planSku && (planLoading || plan) && (
        <SelectedPlanPreview planLoading={planLoading} plan={plan} />
      )}
      <div className="space-y-6">
        <EligibilityStatusAlerts
          isLoading={eligibilityQuery.isLoading}
          isError={eligibilityQuery.isError}
          onRetry={() => void eligibilityQuery.refetch()}
        />
        <SubCard>
          <AddressConfirmation
            embedded
            onAddressConfirmed={handleAddressConfirmed}
            onAddressIncomplete={handleAddressIncomplete}
            orderType={ORDER_TYPE.INTERNET}
            titleOverride="Installation Address"
            confirmationPrompt="Please confirm this is the correct address for your availability request."
          />
        </SubCard>
        <SubmitRequestCard
          autoEligibilityRequest={autoEligibilityRequest}
          submissionError={submissionError}
          submitDisabled={!addressConfirmed || !address || eligibilityRequest.isPending}
          isPending={eligibilityRequest.isPending}
          onSubmit={() => void handleSubmit()}
        />
      </div>
    </div>
  );
}

export default InternetEligibilityRequestView;
