"use client";

import * as React from "react";
import { FileTextIcon } from "lucide-react";

import { Button } from "@/components/ui/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { EmptyState } from "@/components/ui/empty-state";
import { Typography } from "@/components/ui/typography";
import { useTranslation } from "@/hooks/useTranslation";
import { VerificationStatus } from "@/types/provider";
import type { ProviderDocument } from "@/types/provider";

import { DocumentReviewDialog } from "./DocumentReviewDialog";
import { DocumentStatusBadge } from "./ProviderStatusBadge";
import { formatDay } from "./lib/format";

/**
 * KYC document verification.
 *
 * A card list rather than a DataTable: there are at most four documents (one
 * per DocumentType), each needs a multi-line summary plus a review action, and
 * none of the table affordances — search, sort, pagination, bulk select —
 * apply. The DataTable rule is for list *screens*; this is a fixed-size panel.
 */
export function ProviderDocumentsTab({
  providerId,
  documents,
}: {
  providerId: string;
  documents: ProviderDocument[];
}) {
  const { t } = useTranslation();
  const [reviewing, setReviewing] = React.useState<ProviderDocument | null>(
    null,
  );

  if (documents.length === 0) {
    return (
      <Card>
        <CardContent>
          <EmptyState
            icon={<FileTextIcon />}
            title={t("providers.detail.documents.emptyTitle")}
            description={t("providers.detail.documents.emptyDescription")}
          />
        </CardContent>
      </Card>
    );
  }

  return (
    <>
      <Card>
        <CardHeader>
          <CardTitle>{t("providers.detail.documents.title")}</CardTitle>
          <CardDescription>
            {t("providers.detail.documents.description")}
          </CardDescription>
        </CardHeader>
        <CardContent className="flex flex-col gap-3">
          {documents.map((document) => (
            <DocumentRow
              key={document.id}
              document={document}
              onReview={() => setReviewing(document)}
            />
          ))}
        </CardContent>
      </Card>

      <DocumentReviewDialog
        document={reviewing}
        providerId={providerId}
        onClose={() => setReviewing(null)}
      />
    </>
  );
}

function DocumentRow({
  document,
  onReview,
}: {
  document: ProviderDocument;
  onReview: () => void;
}) {
  const { t, language } = useTranslation();

  const verifierName = document.verifiedBy
    ? `${document.verifiedBy.firstName} ${document.verifiedBy.lastName}`.trim()
    : null;

  return (
    <div className="flex flex-col gap-3 rounded-[12px] border border-border bg-white p-4 sm:flex-row sm:items-center sm:justify-between">
      <div className="flex min-w-0 flex-col gap-1.5">
        <div className="flex flex-wrap items-center gap-2">
          <Typography as="span" variant="h3">
            {t(`providers.documentType.${document.documentType}`)}
          </Typography>
          <DocumentStatusBadge status={document.status} />
        </div>

        <Typography as="span" variant="caption" color="secondary">
          {t("providers.detail.documents.uploaded", {
            date: formatDay(document.uploadedAt, language),
          })}
        </Typography>

        {verifierName && document.status !== VerificationStatus.PENDING && (
          <Typography as="span" variant="caption" color="secondary">
            {t("providers.detail.documents.verifiedBy", { name: verifierName })}
          </Typography>
        )}

        {document.status === VerificationStatus.REJECTED &&
          document.rejectionReason && (
            <Typography
              as="span"
              variant="caption"
              className="text-destructive"
            >
              {t("providers.detail.documents.rejectionReason", {
                reason: document.rejectionReason,
              })}
            </Typography>
          )}
      </div>

      <Button variant="secondary" size="sm" onClick={onReview}>
        {t("providers.detail.documents.review")}
      </Button>
    </div>
  );
}
