import React, { useState } from 'react';
import CardBoxModal from './CardBoxModal';
import FormField from './FormField';
import { useAppDispatch, useAppSelector } from '../stores/hooks';
import { create as createReport } from '../stores/reports/reportsSlice';

type Props = {
  isOpen: boolean;
  onClose: () => void;
  targetType: 'user' | 'post' | 'comment' | 'reel' | 'message' | 'story';
  targetRef: string;
};

const REASONS = [
  { value: 'spam', label: 'Spam' },
  { value: 'harassment', label: 'Harassment' },
  { value: 'hate_speech', label: 'Hate Speech' },
  { value: 'nudity', label: 'Nudity' },
  { value: 'violence', label: 'Violence' },
  { value: 'self_harm', label: 'Self Harm' },
  { value: 'scam', label: 'Scam' },
  { value: 'copyright', label: 'Copyright' },
  { value: 'other', label: 'Other' },
];

export default function ReportModal({ isOpen, onClose, targetType, targetRef }: Props) {
  const dispatch = useAppDispatch();
  const { currentUser } = useAppSelector((state) => state.auth);
  const [reason, setReason] = useState('spam');
  const [details, setDetails] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);

  const handleSubmit = async () => {
    if (!currentUser) return;

    setIsSubmitting(true);
    try {
      await dispatch(createReport({
        target_type: targetType,
        target_ref: targetRef,
        reason: reason,
        details: details,
        status: 'open',
        reported_at: new Date().toISOString(),
        reporter: currentUser.id,
      })).unwrap();
      onClose();
      alert('Report submitted successfully.');
    } catch (err) {
      console.error('Failed to submit report', err);
      alert('Failed to submit report.');
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <CardBoxModal
      title="Report Item"
      buttonColor="danger"
      buttonLabel="Submit Report"
      isActive={isOpen}
      onConfirm={handleSubmit}
      onCancel={onClose}
    >
      <FormField label="Reason for report">
        <select 
          className="w-full dark:bg-dark-900 dark:text-white border-gray-300 dark:border-gray-700 rounded-md"
          value={reason}
          onChange={(e) => setReason(e.target.value)}
        >
          {REASONS.map((r) => (
            <option key={r.value} value={r.value}>{r.label}</option>
          ))}
        </select>
      </FormField>
      <FormField label="Details (Optional)">
        <textarea
          className="w-full dark:bg-dark-900 dark:text-white border-gray-300 dark:border-gray-700 rounded-md"
          rows={3}
          value={details}
          onChange={(e) => setDetails(e.target.value)}
          placeholder="Provide more information..."
        />
      </FormField>
      {isSubmitting && <p className="text-sm text-gray-500">Submitting...</p>}
    </CardBoxModal>
  );
}
