// @design-system: domain/ReportButton

'use client';

import { useState } from 'react';
import { cn } from '@/lib/cn';
import { Button } from '@/components/ui/primitives/Button';
import { Icon } from '@/components/ui/icons/Icon';
import { FormField } from '@/components/ui/primitives/FormField';
import {
  Select,
  SelectTrigger,
  SelectValue,
  SelectContent,
  SelectItem,
} from '@/components/ui/primitives/Select';
import { Textarea } from '@/components/ui/primitives/Textarea';
import {
  Dialog,
  DialogTrigger,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from '@/components/ui/overlays/Dialog';
import {
  Tooltip,
  TooltipTrigger,
  TooltipContent,
  TooltipProvider,
} from '@/components/ui/overlays/Tooltip';
import { useT } from '@/lib/i18n/react';
import { captureCaught } from '@/lib/observability';

/** Props for ReportButton */
export interface ReportButtonProps {
  /** Subject being reported (deal id, business id, etc.). */
  targetId: string;
  /** Subject type. */
  targetType: 'DEAL' | 'VENDOR' | 'REVIEW' | 'USER';
  /** Show visible text label alongside the icon. */
  showLabel?: boolean;
  /** Additional class names. */
  className?: string;
}

/**
 * ReportButton - exclamation icon button that opens a report dialog.
 * On submit POSTs to `/api/reports`.
 *
 * @example
 * ```tsx
 * <ReportButton targetId={deal.id} targetType="DEAL" />
 * ```
 */
export function ReportButton({ targetId, targetType, showLabel, className }: ReportButtonProps) {
  const t = useT('domain_report');
  const tCommon = useT('common');
  const tForms = useT('forms');
  const tSupport = useT('support');
  const supportTicket = tSupport('ticket') as unknown as Record<string, string>;
  const [reason, setReason] = useState('');
  const [body, setBody] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [success, setSuccess] = useState(false);
  const [error, setError] = useState<'validation' | 'rate_limit' | 'server' | null>(null);
  const [reported, setReported] = useState(false);
  const [open, setOpen] = useState(false);

  const handleSubmit = async () => {
    if (!reason) return;
    setSubmitting(true);
    setError(null);
    try {
      const res = await fetch('/api/reports', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ targetId, targetType, reason, body }),
      });
      const json = (await res.json()) as { ok: boolean };
      if (!res.ok || !json.ok) {
        setError(res.status === 429 ? 'rate_limit' : res.status < 500 ? 'validation' : 'server');
        return;
      }
      setSuccess(true);
      setReported(true);
      setTimeout(() => {
        setOpen(false);
        setSuccess(false);
        setReason('');
        setBody('');
      }, 1500);
    } catch (err) {
      captureCaught(err, { scope: 'components.ReportButton.submit', severity: 'warning' });
      setError('server');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <Dialog open={reported ? false : open} onOpenChange={reported ? undefined : setOpen}>
      <TooltipProvider>
        <Tooltip open={reported ? undefined : false}>
          <TooltipTrigger asChild>
            <DialogTrigger asChild>
              <Button
                variant="ghost"
                size="sm"
                className={cn(
                  reported
                    ? 'text-danger-600 cursor-not-allowed'
                    : 'text-text-secondary hover:text-danger-600',
                  className,
                )}
                iconStart={<Icon name="Flag" size="sm" />}
                aria-label={t('button_label')}
                disabled={reported}
                aria-disabled={reported}
              >
                <span className={showLabel ? undefined : 'sr-only'}>{t('button_label')}</span>
              </Button>
            </DialogTrigger>
          </TooltipTrigger>
          {reported && <TooltipContent>{t('thank_you')}</TooltipContent>}
        </Tooltip>
      </TooltipProvider>

      <DialogContent>
        <DialogHeader>
          <DialogTitle>{t('button_label')}</DialogTitle>
        </DialogHeader>

        {success ? (
          <p className="text-success-600 py-4 text-center text-sm font-medium">{t('success')}</p>
        ) : (
          <div className="flex flex-col gap-4">
            {error && (
              <p className="text-danger-600 text-sm">
                {error === 'rate_limit'
                  ? supportTicket.error_rate_limited
                  : error === 'validation'
                    ? tForms('invalid')
                    : tCommon('error')}
              </p>
            )}
            <FormField label={t('reason_other')} htmlFor="report-reason">
              <Select value={reason} onValueChange={setReason}>
                <SelectTrigger id="report-reason">
                  <SelectValue placeholder={t('reason_other')} />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="FACTUAL_ERROR">{t('reason_factual')}</SelectItem>
                  <SelectItem value="MISLEADING">{t('reason_misleading')}</SelectItem>
                  <SelectItem value="WRONG_HOURS">{t('reason_hours')}</SelectItem>
                  <SelectItem value="BUG">{t('reason_bug')}</SelectItem>
                  <SelectItem value="OTHER">{t('reason_other')}</SelectItem>
                </SelectContent>
              </Select>
            </FormField>

            <FormField label={t('button_label')} htmlFor="report-detail">
              <Textarea
                id="report-detail"
                rows={3}
                value={body}
                onChange={(e) => setBody(e.target.value)}
              />
            </FormField>
          </div>
        )}

        {!success && (
          <DialogFooter>
            <Button
              variant="primary"
              size="md"
              onClick={handleSubmit}
              loading={submitting}
              disabled={!reason}
            >
              {t('submit')}
            </Button>
          </DialogFooter>
        )}
      </DialogContent>
    </Dialog>
  );
}
