"use client";

import { ShieldCheck } from "lucide-react";
import { SubCard } from "@/components/molecules/SubCard/SubCard";
import { Button } from "@/components/atoms/button";
import { AlertBanner } from "@/components/molecules/AlertBanner/AlertBanner";
import { StatusPill } from "@/components/atoms/status-pill";
import { ResidenceCardUploadInput } from "./ResidenceCardUploadInput";

type VerificationStatus = "verified" | "pending" | "rejected" | "not_submitted" | undefined;

interface VerificationData {
  submittedAt?: string | null | undefined;
  reviewedAt?: string | null | undefined;
  reviewerNotes?: string | null | undefined;
}

interface IdentityVerificationSectionProps {
  isLoading: boolean;
  isError: boolean;
  status: VerificationStatus;
  data?: VerificationData | undefined;
  onRefetch: () => void;
  onSubmitFile: (file: File) => void;
  isSubmitting: boolean;
  submitError?: Error | null | undefined;
  formatDateTime: (iso?: string | null) => string | null;
}

export function IdentityVerificationSection({
  isLoading,
  isError,
  status,
  data,
  onRefetch,
  onSubmitFile,
  isSubmitting,
  submitError,
  formatDateTime,
}: IdentityVerificationSectionProps) {
  const getStatusPill = () => {
    switch (status) {
      case "verified":
        return <StatusPill label="Verified" variant="success" />;
      case "pending":
        return <StatusPill label="Submitted" variant="info" />;
      case "rejected":
        return <StatusPill label="Action needed" variant="warning" />;
      default:
        return <StatusPill label="Required" variant="warning" />;
    }
  };

  const renderContent = () => {
    if (isLoading) {
      return <div className="text-sm text-muted-foreground">Checking residence card status...</div>;
    }

    if (isError) {
      return (
        <AlertBanner
          variant="warning"
          title="Unable to load verification status"
          size="sm"
          elevated
        >
          <Button type="button" size="sm" onClick={onRefetch}>
            Check again
          </Button>
        </AlertBanner>
      );
    }

    if (status === "verified") {
      return (
        <VerifiedContent
          data={data}
          formatDateTime={formatDateTime}
          onSubmitFile={onSubmitFile}
          isSubmitting={isSubmitting}
          submitError={submitError}
        />
      );
    }

    if (status === "pending") {
      return (
        <PendingContent
          data={data}
          formatDateTime={formatDateTime}
          onSubmitFile={onSubmitFile}
          isSubmitting={isSubmitting}
          submitError={submitError}
        />
      );
    }

    return (
      <NotSubmittedContent
        status={status}
        reviewerNotes={data?.reviewerNotes}
        onSubmitFile={onSubmitFile}
        isSubmitting={isSubmitting}
        submitError={submitError}
      />
    );
  };

  return (
    <SubCard
      title="Identity verification"
      icon={<ShieldCheck className="w-5 h-5 text-primary" />}
      right={getStatusPill()}
    >
      {renderContent()}
    </SubCard>
  );
}

interface VerifiedContentProps {
  data?: VerificationData | undefined;
  formatDateTime: (iso?: string | null) => string | null;
  onSubmitFile: (file: File) => void;
  isSubmitting: boolean;
  submitError?: Error | null | undefined;
}

function VerifiedContent({
  data,
  formatDateTime,
  onSubmitFile,
  isSubmitting,
  submitError,
}: VerifiedContentProps) {
  return (
    <div className="space-y-3">
      <AlertBanner variant="success" title="Residence card verified" size="sm" elevated>
        Your identity verification is complete.
      </AlertBanner>

      {(data?.submittedAt || data?.reviewedAt) && (
        <div className="rounded-xl border border-border bg-muted/30 px-4 py-3">
          <div className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
            Verification status
          </div>
          <div className="mt-1 text-xs text-muted-foreground space-y-0.5">
            {formatDateTime(data?.submittedAt) && (
              <div>Submitted: {formatDateTime(data?.submittedAt)}</div>
            )}
            {formatDateTime(data?.reviewedAt) && (
              <div>Reviewed: {formatDateTime(data?.reviewedAt)}</div>
            )}
          </div>
        </div>
      )}

      <details className="rounded-xl border border-border bg-card p-4">
        <summary className="cursor-pointer select-none text-sm font-semibold text-foreground">
          Replace residence card
        </summary>
        <div className="pt-3">
          <ResidenceCardUploadInput
            onSubmit={onSubmitFile}
            isPending={isSubmitting}
            isError={!!submitError}
            error={submitError}
            submitLabel="Submit replacement"
            description="Replacing the file restarts the verification process."
          />
        </div>
      </details>
    </div>
  );
}

interface PendingContentProps {
  data?: VerificationData | undefined;
  formatDateTime: (iso?: string | null) => string | null;
  onSubmitFile: (file: File) => void;
  isSubmitting: boolean;
  submitError?: Error | null | undefined;
}

function PendingContent({
  data,
  formatDateTime,
  onSubmitFile,
  isSubmitting,
  submitError,
}: PendingContentProps) {
  return (
    <div className="space-y-3">
      <AlertBanner variant="info" title="Residence card submitted" size="sm" elevated>
        We'll verify your residence card before activating SIM service.
      </AlertBanner>

      {data?.submittedAt && (
        <div className="rounded-xl border border-border bg-muted/30 px-4 py-3">
          <div className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
            Submission status
          </div>
          <div className="mt-1 text-xs text-muted-foreground">
            Submitted: {formatDateTime(data?.submittedAt)}
          </div>
        </div>
      )}

      <details className="rounded-xl border border-border bg-card p-4">
        <summary className="cursor-pointer select-none text-sm font-semibold text-foreground">
          Replace residence card
        </summary>
        <div className="pt-3">
          <ResidenceCardUploadInput
            onSubmit={onSubmitFile}
            isPending={isSubmitting}
            isError={!!submitError}
            error={submitError}
            submitLabel="Submit replacement"
            description="If you uploaded the wrong file, you can replace it. This restarts the review."
          />
        </div>
      </details>
    </div>
  );
}

interface NotSubmittedContentProps {
  status: VerificationStatus;
  reviewerNotes?: string | null | undefined;
  onSubmitFile: (file: File) => void;
  isSubmitting: boolean;
  submitError?: Error | null | undefined;
}

function NotSubmittedContent({
  status,
  reviewerNotes,
  onSubmitFile,
  isSubmitting,
  submitError,
}: NotSubmittedContentProps) {
  const isRejected = status === "rejected";

  return (
    <AlertBanner
      variant={isRejected ? "warning" : "info"}
      title={isRejected ? "ID verification rejected" : "Submit your residence card"}
      size="sm"
      elevated
    >
      <div className="space-y-3">
        {isRejected && reviewerNotes ? (
          <div className="text-sm text-foreground/80">
            <div className="font-medium text-foreground">Rejection note</div>
            <div>{reviewerNotes}</div>
          </div>
        ) : isRejected ? (
          <p className="text-sm text-foreground/80">
            Your document couldn't be approved. Please upload a new file to continue.
          </p>
        ) : null}

        <p className="text-sm text-foreground/80">
          Upload a JPG, PNG, or PDF (max 5MB). We'll verify it before activating SIM service.
        </p>

        <ResidenceCardUploadInput
          onSubmit={onSubmitFile}
          isPending={isSubmitting}
          isError={!!submitError}
          error={submitError}
          submitLabel="Submit for review"
        />
      </div>
    </AlertBanner>
  );
}
