"use client";

import type { UseQueryResult } from "@tanstack/react-query";
import { ShieldCheckIcon } from "@heroicons/react/24/outline";
import { Skeleton } from "@/components/atoms/loading-skeleton";
import { AlertBanner } from "@/components/molecules/AlertBanner/AlertBanner";
import { Button } from "@/components/atoms/button";
import { StatusPill } from "@/components/atoms/status-pill";
import { formatIsoDate } from "@/shared/utils";
import type { ResidenceCardVerification } from "@customer-portal/domain/customer";
import type { useVerificationFileUpload } from "@/features/verification/hooks";

type VerificationQuery = UseQueryResult<ResidenceCardVerification, Error>;
type FileUpload = ReturnType<typeof useVerificationFileUpload>;

interface VerificationCardProps {
  verificationQuery: VerificationQuery;
  fileUpload: FileUpload;
}

function VerificationStatusPill({
  status,
  isLoading,
}: {
  status?: string | undefined;
  isLoading: boolean;
}) {
  if (isLoading) {
    return <Skeleton className="h-6 w-20" />;
  }
  switch (status) {
    case "verified":
      return <StatusPill label="Verified" variant="success" />;
    case "pending":
      return <StatusPill label="Under Review" variant="info" />;
    case "rejected":
      return <StatusPill label="Action Needed" variant="warning" />;
    default:
      return <StatusPill label="Required for SIM" variant="warning" />;
  }
}

function VerificationContent({
  data,
  status,
  isLoading,
}: {
  data: ResidenceCardVerification | undefined;
  status?: string | undefined;
  isLoading: boolean;
}) {
  if (isLoading) {
    return (
      <div className="space-y-3">
        <Skeleton className="h-4 w-48" />
        <Skeleton className="h-4 w-32" />
      </div>
    );
  }

  if (status === "verified") {
    return (
      <div className="space-y-2">
        <p className="text-sm text-muted-foreground">
          Your identity has been verified. No further action is needed.
        </p>
        {data?.reviewedAt && (
          <p className="text-xs text-muted-foreground">
            Verified on {formatIsoDate(data.reviewedAt, { dateStyle: "medium" })}
          </p>
        )}
      </div>
    );
  }

  if (status === "pending") {
    return (
      <div className="space-y-4">
        <AlertBanner variant="info" title="Under review" size="sm" elevated>
          Your residence card has been submitted. We&apos;ll verify it before activating SIM
          service.
        </AlertBanner>
        {data?.submittedAt && (
          <div className="rounded-lg border border-border bg-muted/30 px-4 py-3">
            <div className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
              Submission status
            </div>
            <div className="mt-1 text-xs text-muted-foreground">
              Submitted on {formatIsoDate(data.submittedAt, { dateStyle: "medium" })}
            </div>
          </div>
        )}
      </div>
    );
  }

  return null;
}

function UploadStatusMessage({
  status,
  reviewerNotes,
}: {
  status?: string | undefined;
  reviewerNotes?: string | null | undefined;
}) {
  if (status === "rejected") {
    return (
      <AlertBanner variant="warning" title="Verification rejected" size="sm" elevated>
        <div className="space-y-2">
          {reviewerNotes && <p>{reviewerNotes}</p>}
          <p>Please upload a new, clear photo or scan of your residence card.</p>
          <ul className="list-disc space-y-1 pl-5 text-sm text-muted-foreground">
            <li>Make sure all text is readable and the full card is visible.</li>
            <li>Avoid glare/reflections and blurry photos.</li>
            <li>Maximum file size: 5MB.</li>
          </ul>
        </div>
      </AlertBanner>
    );
  }
  return (
    <p className="text-sm text-muted-foreground">
      Upload your residence card to activate SIM services. This is required for SIM orders.
    </p>
  );
}

function SubmissionHistory({
  submittedAt,
  reviewedAt,
}: {
  submittedAt?: string | null | undefined;
  reviewedAt?: string | null | undefined;
}) {
  if (!submittedAt && !reviewedAt) return null;
  return (
    <div className="rounded-lg border border-border bg-muted/30 px-4 py-3">
      <div className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
        Latest submission
      </div>
      {submittedAt && (
        <div className="mt-1 text-xs text-muted-foreground">
          Submitted on {formatIsoDate(submittedAt, { dateStyle: "medium" })}
        </div>
      )}
      {reviewedAt && (
        <div className="mt-1 text-xs text-muted-foreground">
          Reviewed on {formatIsoDate(reviewedAt, { dateStyle: "medium" })}
        </div>
      )}
    </div>
  );
}

function FileUploadControls({ fileUpload }: { fileUpload: FileUpload }) {
  if (!fileUpload.canUpload) return null;
  return (
    <div className="space-y-3">
      <input
        ref={fileUpload.inputRef}
        type="file"
        accept="image/*,application/pdf"
        onChange={e => fileUpload.handleFileChange(e.target.files?.[0] ?? null)}
        className="block w-full text-sm text-foreground file:mr-4 file:py-2 file:px-3 file:rounded-md file:border-0 file:text-sm file:font-medium file:bg-muted file:text-foreground hover:file:bg-muted/80"
      />
      {fileUpload.file && (
        <div className="flex items-center justify-between gap-3 rounded-lg border border-border bg-muted/30 px-3 py-2">
          <div className="min-w-0">
            <div className="text-xs font-medium text-muted-foreground">Selected file</div>
            <div className="text-sm font-medium text-foreground truncate">
              {fileUpload.file.name}
            </div>
          </div>
          <Button type="button" variant="outline" size="sm" onClick={fileUpload.clearFile}>
            Change
          </Button>
        </div>
      )}
      <div className="flex items-center justify-end">
        <Button
          type="button"
          disabled={!fileUpload.file || fileUpload.isSubmitting}
          isLoading={fileUpload.isSubmitting}
          loadingText="Uploading..."
          onClick={fileUpload.submit}
        >
          Submit Document
        </Button>
      </div>
      {fileUpload.isError && (
        <p className="text-sm text-destructive">
          {fileUpload.error instanceof Error
            ? fileUpload.error.message
            : "Failed to submit residence card."}
        </p>
      )}
      <p className="text-xs text-muted-foreground">
        Accepted formats: JPG, PNG, or PDF (max 5MB). Make sure all text is readable.
      </p>
    </div>
  );
}

function UploadSection({
  data,
  status,
  fileUpload,
}: {
  data: ResidenceCardVerification | undefined;
  status?: string | undefined;
  fileUpload: FileUpload;
}) {
  if (status === "verified" || status === "pending") return null;
  return (
    <div className="space-y-4">
      <UploadStatusMessage status={status} reviewerNotes={data?.reviewerNotes} />
      <SubmissionHistory submittedAt={data?.submittedAt} reviewedAt={data?.reviewedAt} />
      <FileUploadControls fileUpload={fileUpload} />
    </div>
  );
}

export function VerificationCard({ verificationQuery, fileUpload }: VerificationCardProps) {
  const verificationStatus = verificationQuery.data?.status;

  return (
    <div className="bg-card text-card-foreground rounded-xl border border-border shadow-[var(--cp-shadow-1)]">
      <div className="px-6 py-5 border-b border-border">
        <div className="flex items-center justify-between">
          <div className="flex items-center space-x-3">
            <ShieldCheckIcon className="h-6 w-6 text-primary" />
            <h2 className="text-xl font-semibold text-foreground">Identity Verification</h2>
          </div>
          <VerificationStatusPill
            status={verificationStatus}
            isLoading={verificationQuery.isLoading}
          />
        </div>
      </div>

      <div className="p-6">
        <VerificationContent
          data={verificationQuery.data}
          status={verificationStatus}
          isLoading={verificationQuery.isLoading}
        />

        {!verificationQuery.isLoading && (
          <UploadSection
            data={verificationQuery.data}
            status={verificationStatus}
            fileUpload={fileUpload}
          />
        )}
      </div>
    </div>
  );
}
