import { useState } from 'react';
import { Pill } from '@/components/ui/primitives/Pill';
import { StatusBadge } from '@/components/ui/domain/StatusBadge/StatusBadge';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/overlays/AlertDialog';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/primitives/Select/Select';
import { useT } from '@/lib/i18n/react';
import { STRIPE_ONBOARDING_STATUS_MAP, VENDOR_STATE_STATUS_MAP } from './VendorDetail.types';

export function InfoRow({
  label,
  value,
  labelTooltip,
}: {
  label: string;
  value: React.ReactNode;
  labelTooltip?: string;
}) {
  return (
    <div className="border-border-default grid grid-cols-2 gap-2 border-b py-2 last:border-0">
      <dt className="text-text-secondary text-sm" title={labelTooltip}>
        {label}
      </dt>
      <dd className="text-text-primary text-sm font-medium">{value}</dd>
    </div>
  );
}

export function SectionTitle({ children }: { children: React.ReactNode }) {
  return <h2 className="mb-3 text-2xl font-[var(--font-weight-extrabold)]">{children}</h2>;
}

export function Card({ children }: { children: React.ReactNode }) {
  return <div className="bg-surface-default rounded-2xl p-4 shadow-md">{children}</div>;
}

export function AccountStateBadge({ state }: { state: string }) {
  return (
    <StatusBadge state={state} map={VENDOR_STATE_STATUS_MAP} ns="admin_vendor_detail" size="sm" />
  );
}

export function TierBadge({ tier }: { tier: string }) {
  const t = useT('admin_vendor_detail');
  const label = (t as (k: string) => string)(`tier_${tier}`) || tier;
  return (
    <Pill tone={tier === 'VETERAN' ? 'info' : 'neutral'} size="sm">
      {label}
    </Pill>
  );
}

export function StripeOnboardingBadge({ state }: { state: string | null }) {
  const t = useT('admin_vendor_detail');
  if (!state) {
    return (
      <Pill tone="neutral" size="sm">
        {(t as (k: string) => string)('stripe_state_none')}
      </Pill>
    );
  }

  return (
    <StatusBadge
      state={state}
      map={STRIPE_ONBOARDING_STATUS_MAP}
      ns="admin_vendor_detail"
      size="sm"
    />
  );
}

interface DayHoursProps {
  dayLabel: string;
  open: string | null;
  close: string | null;
  closed: boolean;
  closedLabel: string;
}

export function DayHours({ dayLabel, open, close, closed, closedLabel }: DayHoursProps) {
  return (
    <div className="border-border-default grid grid-cols-2 gap-2 border-b py-2 last:border-0">
      <dt className="text-text-secondary text-sm">{dayLabel}</dt>
      <dd className="text-text-primary text-sm">
        {closed ? (
          <span className="text-text-secondary italic">{closedLabel}</span>
        ) : (
          `${open ?? '?'} - ${close ?? '?'}`
        )}
      </dd>
    </div>
  );
}

interface TierSelectProps {
  currentTier: 'NEW' | 'VETERAN';
  disabled: boolean;
  onTierChange: (tier: 'NEW' | 'VETERAN') => void;
}

export function TierSelect({ currentTier, disabled, onTierChange }: TierSelectProps) {
  const tAdmin = useT('admin');
  const tCommon = useT('common');
  const [confirmDowngrade, setConfirmDowngrade] = useState(false);
  const [pendingTier, setPendingTier] = useState<'NEW' | 'VETERAN' | null>(null);

  function handleValueChange(value: string) {
    const tier = value as 'NEW' | 'VETERAN';
    if (tier === 'NEW' && currentTier === 'VETERAN') {
      setPendingTier(tier);
      setConfirmDowngrade(true);
      return;
    }

    onTierChange(tier);
  }

  return (
    <>
      <Select value={currentTier} onValueChange={handleValueChange} disabled={disabled}>
        <SelectTrigger className="w-36">
          <SelectValue />
        </SelectTrigger>
        <SelectContent>
          <SelectItem value="NEW">{(tAdmin as (k: string) => string)('tier_new')}</SelectItem>
          <SelectItem value="VETERAN">
            {(tAdmin as (k: string) => string)('tier_veteran')}
          </SelectItem>
        </SelectContent>
      </Select>

      <AlertDialog open={confirmDowngrade} onOpenChange={setConfirmDowngrade}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>
              {(tAdmin as (k: string) => string)('tier_downgrade_confirm_title')}
            </AlertDialogTitle>
            <AlertDialogDescription>
              {(tAdmin as (k: string) => string)('tier_downgrade_confirm_desc')}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogAction
              onClick={() => {
                setConfirmDowngrade(false);
                if (pendingTier) onTierChange(pendingTier);
              }}
            >
              {(tAdmin as (k: string) => string)('tier_downgrade_confirm_title')}
            </AlertDialogAction>
            <AlertDialogCancel>{tCommon('cancel')}</AlertDialogCancel>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
}

export function isDealState(state: string) {
  return ['ACTIVE', 'PENDING_APPROVAL', 'REJECTED', 'EXPIRED', 'SOLD_OUT', 'PAUSED'].includes(
    state,
  );
}
