"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 { ORDER_TYPE } from "@customer-portal/domain/orders";

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,
  ]);

  const submitDisabled = !addressConfirmed || !address || eligibilityRequest.isPending;

  // If request is already locked, show status and redirect option
  if (isRequestLocked) {
    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">
          {eligibilityStatus === "pending" && (
            <AlertBanner variant="info" title="Availability review already in progress" elevated>
              <div className="flex flex-col sm:flex-row sm:items-center gap-3">
                <span className="text-sm text-foreground/80">
                  We&apos;re already verifying your address. You&apos;ll receive an update when
                  it&apos;s complete.
                </span>
                <Button
                  as="a"
                  href={`${servicesBasePath}/internet`}
                  size="sm"
                  className="sm:ml-auto"
                >
                  View status
                </Button>
              </div>
            </AlertBanner>
          )}

          {eligibilityStatus === "eligible" && (
            <AlertBanner variant="success" title="You're already eligible" elevated>
              <div className="flex flex-col sm:flex-row sm:items-center gap-3">
                <span className="text-sm text-foreground/80">
                  Your address is eligible. You can select a plan and continue.
                </span>
                <Button
                  as="a"
                  href={`${servicesBasePath}/internet`}
                  size="sm"
                  className="sm:ml-auto"
                >
                  View plans
                </Button>
              </div>
            </AlertBanner>
          )}

          {eligibilityStatus === "ineligible" && (
            <AlertBanner variant="warning" title="Service not available" elevated>
              <div className="flex flex-col sm:flex-row sm:items-center gap-3">
                <span className="text-sm text-foreground/80">
                  Our team determined service isn&apos;t available at your address.
                </span>
                <Button as="a" href="/account/support/new" size="sm" className="sm:ml-auto">
                  Contact support
                </Button>
              </div>
            </AlertBanner>
          )}
        </div>
      </div>
    );
  }

  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-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>

      {planSku && (planLoading || plan) && (
        <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">
              {planLoading ? (
                <div className="text-sm text-muted-foreground">Loading selected plan…</div>
              ) : plan ? (
                <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>
              ) : null}
            </div>
          </div>
        </div>
      )}

      <div className="space-y-6">
        {eligibilityQuery.isLoading && (
          <AlertBanner variant="info" title="Checking availability status" elevated>
            We&apos;re loading your latest eligibility status.
          </AlertBanner>
        )}

        {eligibilityQuery.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={() => void eligibilityQuery.refetch()}
              >
                Try again
              </Button>
            </div>
          </AlertBanner>
        )}

        <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>

        <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={() => void handleSubmit()}
                disabled={submitDisabled}
                isLoading={eligibilityRequest.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>
      </div>
    </div>
  );
}

export default InternetEligibilityRequestView;
