'use client';

import { useState, useEffect, useRef } from 'react';
import toast from 'react-hot-toast';
import { getApiErrorMessage } from '@/lib/utils/apiError';

interface ReviewData {
  id: string;
  product_name: string;
  reviewer_name: string;
  rating: number;
  title: string | null;
  content: string;
}

interface EditReviewModalProps {
  isOpen: boolean;
  review: ReviewData | null;
  onClose: () => void;
  onSaved: () => void;
}

const RATINGS = [5, 4, 3, 2, 1];

export default function EditReviewModal({ isOpen, review, onClose, onSaved }: EditReviewModalProps) {
  const [rating, setRating] = useState(5);
  const [title, setTitle] = useState('');
  const [content, setContent] = useState('');
  const [loading, setLoading] = useState(false);
  const [errors, setErrors] = useState<Record<string, string>>({});

  const prevReviewRef = useRef<string | null>(null);

  useEffect(() => {
    if (isOpen && review && review.id !== prevReviewRef.current) {
      prevReviewRef.current = review.id;
      setRating(review.rating);
      setTitle(review.title || '');
      setContent(review.content);
      setErrors({});
    }
    if (!isOpen) {
      prevReviewRef.current = null;
    }
  }, [isOpen, review]);

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

    const newErrors: Record<string, string> = {};
    if (!content.trim()) newErrors.content = 'Review content is required';
    if (Object.keys(newErrors).length > 0) {
      setErrors(newErrors);
      return;
    }

    setLoading(true);
    try {
      const res = await fetch(`/api/reviews/${review.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ rating, title: title.trim() || null, content: content.trim() }),
      });

      if (res.ok) {
        toast.success('Review updated');
        onSaved();
        onClose();
      } else {
        const data = await res.json();
        toast.error(getApiErrorMessage(data, 'Failed to update review'));
      }
    } catch {
      toast.error('Network error');
    } finally {
      setLoading(false);
    }
  };

  if (!isOpen || !review) return null;

  return (
    <div className="fixed inset-0 z-60 flex items-center justify-center p-4" style={{ background: 'rgba(0,0,0,0.5)' }}>
      <div className="rounded-lg p-6 w-full max-w-md max-h-[90vh] overflow-y-auto" style={{
        background: 'var(--color-surface)', border: '1px solid var(--color-border)', boxShadow: 'var(--shadow-card-lg)',
      }}>
        <h3 className="text-lg font-semibold mb-1" style={{ color: 'var(--color-text)' }}>Edit Review</h3>
        <p className="text-xs mb-4" style={{ color: 'var(--color-text-tertiary)' }}>
          {review.product_name} — by {review.reviewer_name}
        </p>

        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium mb-1">Rating</label>
            <select value={rating} onChange={(e) => setRating(Number(e.target.value))}
              className="w-full px-3 py-2 rounded-lg text-sm"
              style={{ background: 'var(--color-surface-alt)', border: '1px solid var(--color-border)', color: 'var(--color-text)' }}>
              {RATINGS.map((r) => <option key={r} value={r}>{r} Star{r > 1 ? 's' : ''}</option>)}
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium mb-1">Title</label>
            <input type="text" value={title} onChange={(e) => setTitle(e.target.value)}
              className="w-full px-3 py-2 rounded-lg text-sm"
              style={{ background: 'var(--color-surface-alt)', border: '1px solid var(--color-border)', color: 'var(--color-text)' }} />
          </div>

          <div>
            <label className="block text-sm font-medium mb-1">Content <span className="text-red-500">*</span></label>
            <textarea value={content} onChange={(e) => { setContent(e.target.value); setErrors((p) => ({ ...p, content: '' })); }}
              rows={5} className="w-full px-3 py-2 rounded-lg text-sm resize-none"
              style={{ background: 'var(--color-surface-alt)', border: errors.content ? '1px solid var(--color-danger)' : '1px solid var(--color-border)', color: 'var(--color-text)' }} />
            {errors.content && <p className="text-xs mt-1 text-red-500">{errors.content}</p>}
          </div>
        </div>

        <div className="flex gap-3 justify-end mt-6">
          <button onClick={onClose} className="px-4 py-2 rounded-lg text-sm"
            style={{ background: 'var(--color-surface-alt)', color: 'var(--color-text)', border: '1px solid var(--color-border)' }}>Cancel</button>
          <button onClick={handleSubmit} disabled={loading}
            className="px-4 py-2 rounded-lg text-sm text-white disabled:opacity-50"
            style={{ background: 'var(--color-cta)' }}>{loading ? 'Saving...' : 'Save Changes'}</button>
        </div>
      </div>
    </div>
  );
}
