'use client';

import * as React from 'react';
import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { type FlagReason, listingsApi } from '@/lib/listings-api';

const FLAG_REASONS: { value: FlagReason; label: string }[] = [
  { value: 'SCAM', label: 'Lừa đảo / Scam' },
  { value: 'DUPLICATE', label: 'Tin trùng lặp' },
  { value: 'WRONG_INFO', label: 'Thông tin sai lệch' },
  { value: 'ALREADY_SOLD', label: 'Đã bán / Cho thuê rồi' },
  { value: 'INAPPROPRIATE', label: 'Nội dung không phù hợp' },
];

interface ReportListingModalProps {
  listingId: string;
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

export function ReportListingModal({ listingId, open, onOpenChange }: ReportListingModalProps) {
  const [reason, setReason] = React.useState<FlagReason | ''>('');
  const [description, setDescription] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState<string | null>(null);
  const [success, setSuccess] = React.useState(false);

  const handleSubmit = async () => {
    if (!reason) return;
    setLoading(true);
    setError(null);
    try {
      await listingsApi.reportListing(listingId, reason, description || undefined);
      setSuccess(true);
      setTimeout(() => {
        onOpenChange(false);
        setSuccess(false);
        setReason('');
        setDescription('');
      }, 2000);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Không thể gửi báo cáo');
    } finally {
      setLoading(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>Báo cáo tin đăng</DialogTitle>
          <DialogDescription>
            Chọn lý do báo cáo. Chúng tôi sẽ xem xét và xử lý trong thời gian sớm nhất.
          </DialogDescription>
        </DialogHeader>

        {success ? (
          <div className="py-6 text-center">
            <div className="mx-auto mb-3 flex h-12 w-12 items-center justify-center rounded-full bg-green-100">
              <svg className="h-6 w-6 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
              </svg>
            </div>
            <p className="font-medium text-green-700">Báo cáo thành công!</p>
            <p className="mt-1 text-sm text-muted-foreground">Cảm ơn bạn đã giúp cộng đồng.</p>
          </div>
        ) : (
          <>
            <div className="space-y-4 py-2">
              <div className="space-y-2">
                <Label>Lý do báo cáo *</Label>
                <div className="space-y-2">
                  {FLAG_REASONS.map((opt) => (
                    <label
                      key={opt.value}
                      className={`flex cursor-pointer items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50 ${
                        reason === opt.value ? 'border-primary bg-primary/5' : ''
                      }`}
                    >
                      <input
                        type="radio"
                        name="flag-reason"
                        value={opt.value}
                        checked={reason === opt.value}
                        onChange={() => setReason(opt.value)}
                        className="h-4 w-4 text-primary"
                      />
                      <span className="text-sm">{opt.label}</span>
                    </label>
                  ))}
                </div>
              </div>

              <div className="space-y-2">
                <Label htmlFor="report-desc">Mô tả chi tiết (tuỳ chọn)</Label>
                <Textarea
                  id="report-desc"
                  value={description}
                  onChange={(e) => setDescription(e.target.value)}
                  placeholder="Nhập thông tin chi tiết về vấn đề bạn gặp..."
                  maxLength={1000}
                  rows={3}
                />
              </div>

              {error && (
                <p className="text-sm text-destructive">{error}</p>
              )}
            </div>

            <DialogFooter>
              <Button variant="outline" onClick={() => onOpenChange(false)} disabled={loading}>
                Huỷ
              </Button>
              <Button
                onClick={handleSubmit}
                disabled={!reason || loading}
                variant="destructive"
              >
                {loading ? 'Đang gửi...' : 'Gửi báo cáo'}
              </Button>
            </DialogFooter>
          </>
        )}
      </DialogContent>
    </Dialog>
  );
}
