import Loader from '@/components/common/loader';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Separator } from '@/components/ui/separator';
import { Textarea } from '@/components/ui/textarea';
import { updateKycStatus } from '@/data/admin/kyc/update-kyc-status';
import { useApiSWR } from '@/hooks/useSWR';
import type { Kyc, KycStatus } from '@/types';
import { getImageUrl } from '@/utils/getImageUrl';
import {
  CheckCircleIcon,
  ClockIcon,
  FileTextIcon,
  ShieldCheckIcon,
  ShieldSlashIcon,
  ShieldWarningIcon,
  XCircleIcon,
} from '@phosphor-icons/react';
import dayjs from 'dayjs';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { toast } from 'sonner';

const isFilePath = (value: string) =>
  value.includes('/') || value.match(/\.(jpg|jpeg|png|gif|webp|pdf)$/i);

const isImagePath = (value: string) =>
  value.match(/\.(jpg|jpeg|png|gif|webp)$/i);

type StatusConfig = {
  labelKey: string;
  banner: string;
  variant: 'warning' | 'success' | 'destructive' | 'default';
  Icon: React.ElementType;
  iconClass: string;
};

const STATUS_CONFIG: Record<KycStatus, StatusConfig> = {
  pending: {
    labelKey: 'Pending Review',
    banner: 'border-warning/20 bg-warning/5',
    variant: 'warning',
    Icon: ClockIcon,
    iconClass: 'text-warning',
  },
  approved: {
    labelKey: 'Approved',
    banner: 'border-primary/20 bg-primary/5',
    variant: 'success',
    Icon: ShieldCheckIcon,
    iconClass: 'text-primary',
  },
  rejected: {
    labelKey: 'Rejected',
    banner: 'border-warning/20 bg-warning/5',
    variant: 'warning',
    Icon: ShieldWarningIcon,
    iconClass: 'text-warning',
  },
  hard_rejected: {
    labelKey: 'Hard Rejected',
    banner: 'border-destructive/20 bg-destructive/5',
    variant: 'destructive',
    Icon: ShieldSlashIcon,
    iconClass: 'text-destructive',
  },
};

function FieldValue({ name, value }: { name: string; value: string }) {
  const label = name.replace(/_/g, ' ');
  const { t } = useTranslation();

  if (isFilePath(value)) {
    return (
      <div className="rounded-2xl border border-black/5 p-4">
        <p className="mb-3 text-xs font-semibold tracking-wide text-black/40 uppercase">
          {label}
        </p>
        {isImagePath(value) ? (
          <div className="overflow-hidden rounded-xl border border-black/5">
            <img
              src={getImageUrl(value)}
              alt={label}
              className="h-44 w-full object-cover"
              onError={(e) => {
                (e.currentTarget as HTMLImageElement).style.display = 'none';
                e.currentTarget.nextElementSibling?.classList.remove('hidden');
              }}
            />
            <div className="hidden h-44 flex-col items-center justify-center gap-2 bg-black/3">
              <FileTextIcon
                weight="duotone"
                className="size-10 text-black/20"
              />
              <p className="text-xs text-black/30">{t('Image unavailable')}</p>
            </div>
          </div>
        ) : (
          <div className="flex h-24 flex-col items-center justify-center gap-2 rounded-xl border border-dashed border-black/10 bg-black/2">
            <FileTextIcon weight="duotone" className="size-8 text-black/25" />
            <p className="text-xs text-black/40">{t('Document')}</p>
          </div>
        )}
        <p className="mt-2 truncate text-xs text-black/30">{value}</p>
      </div>
    );
  }

  return (
    <div className="rounded-2xl border border-black/5 p-4">
      <p className="mb-1 text-xs font-semibold tracking-wide text-black/40 uppercase">
        {label}
      </p>
      <p className="text-sm font-medium">{value || '-'}</p>
    </div>
  );
}

export default function Kyc({ userId }: { userId: string }) {
  const { t } = useTranslation();
  const apiUrl = `/admin/kycs/${userId}/user`;
  const { data: kyc, isLoading, mutate } = useApiSWR<Kyc>(apiUrl);

  const [remarks, setRemarks] = useState(kyc?.remarks ?? '');
  const [submitting, setSubmitting] = useState(false);

  async function handleAction(status: KycStatus) {
    if (!kyc) return;
    setSubmitting(true);
    const result = await updateKycStatus({ id: kyc.id, status, remarks });
    setSubmitting(false);
    if (result?.success) {
      toast.success(result.message ?? t('KYC status updated'));
      mutate();
    }
  }

  if (isLoading) return <Loader />;

  if (!kyc) {
    return (
      <div className="flex h-64 flex-col items-center justify-center gap-2 rounded-2xl border border-black/5">
        <ShieldCheckIcon weight="duotone" className="size-10 text-black/20" />
        <p className="text-sm text-black/40">
          {t('No KYC submission found for this user.')}
        </p>
      </div>
    );
  }

  const cfg = STATUS_CONFIG[kyc.status];
  const Icon = cfg.Icon;
  const isPending = kyc.status === 'pending';
  const isApproved = kyc.status === 'approved';
  const isRejected =
    kyc.status === 'rejected' || kyc.status === 'hard_rejected';

  return (
    <div className="space-y-5 py-4">
      <div
        className={`flex flex-wrap items-center justify-between gap-2 rounded-2xl border p-4 ${cfg.banner}`}
      >
        <div className="flex items-center gap-3">
          <Icon weight="fill" className={`size-6 ${cfg.iconClass}`} />
          <div>
            <p className="text-xs text-black/50">{t('KYC Module')}</p>
            <p className="text-lg font-semibold">{kyc.type}</p>
          </div>
        </div>
        <div className="text-right">
          <Badge variant={cfg.variant} className="mb-1 px-3 py-1 capitalize">
            {t(cfg.labelKey)}
          </Badge>
          <p className="text-xs text-black/40">
            {t('Submitted')}{' '}
            {dayjs(kyc.created_at).format('MMM D, YYYY · h:mm A')}
          </p>
        </div>
      </div>

      <div>
        <h4 className="mb-3 text-xs font-semibold tracking-widest text-black/30 uppercase">
          {t('Submitted Information')}
        </h4>
        <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 md:grid-cols-3">
          {Object.entries(kyc.data).map(([key, value]) => (
            <FieldValue key={key} name={key} value={value} />
          ))}
        </div>
      </div>

      <Separator />

      <div className="rounded-2xl border border-black/5 p-5">
        <h4 className="mb-3 text-xs font-semibold tracking-widest text-black/30 uppercase">
          {t('Admin Decision')}
        </h4>

        {(isApproved || isRejected) && kyc.remarks && (
          <div
            className={`mb-4 rounded-xl px-4 py-3 text-sm ${
              isApproved
                ? 'bg-primary/5 text-primary'
                : 'bg-destructive/5 text-destructive'
            }`}
          >
            <span className="font-semibold">{t('Remarks')}: </span>
            {kyc.remarks}
          </div>
        )}

        <div className="mb-4">
          <p className="mb-2 text-sm text-black/50">
            {isPending ? t('Add remarks (optional)') : t('Update remarks')}
          </p>
          <Textarea
            value={remarks}
            onChange={(e) => setRemarks(e.target.value)}
            placeholder={t('Enter remarks for the user...')}
            className="min-h-20 resize-none"
            disabled={!isPending || submitting}
          />
        </div>

        {isPending && (
          <div className="flex flex-col gap-3 sm:flex-row">
            <Button
              variant="outline"
              className="flex-1 gap-2 border-success/30 text-success hover:bg-success/5"
              disabled={submitting}
              onClick={() => handleAction('approved')}
            >
              <CheckCircleIcon weight="bold" className="size-4" />
              {t('Approve KYC')}
            </Button>
            <Button
              variant="outline"
              className="flex-1 gap-2 border-warning/30 text-warning hover:bg-warning/5"
              disabled={submitting}
              onClick={() => handleAction('rejected')}
            >
              <XCircleIcon weight="bold" className="size-4" />
              {t('Reject KYC')}
            </Button>
            <Button
              variant="outline"
              className="flex-1 gap-2 border-destructive/30 text-destructive hover:bg-destructive/5"
              disabled={submitting}
              onClick={() => handleAction('hard_rejected')}
            >
              <ShieldSlashIcon weight="bold" className="size-4" />
              {t('Hard Reject')}
            </Button>
          </div>
        )}

        {isApproved && (
          <div className="flex items-center gap-2 rounded-xl bg-primary/5 px-4 py-3">
            <ShieldCheckIcon
              weight="fill"
              className="size-5 shrink-0 text-primary"
            />
            <p className="text-sm font-medium text-primary">
              {t('This KYC submission has been approved.')}
            </p>
          </div>
        )}

        {isRejected && (
          <div className="flex items-center gap-2 rounded-xl bg-destructive/5 px-4 py-3">
            <XCircleIcon
              weight="fill"
              className="size-5 shrink-0 text-destructive"
            />
            <p className="text-sm font-medium text-destructive">
              {t('This KYC submission has been rejected.')}
            </p>
          </div>
        )}
      </div>
    </div>
  );
}
