'use client';

import { useState, useEffect, useRef } from 'react';
import ImageUpload from '@/components/ui/ImageUpload';
import toast from 'react-hot-toast';
import { getApiErrorMessage } from '@/lib/utils/apiError';
import { useCurrencyStore } from '@/store/currencyStore';

interface EditPaymentModalProps {
  isOpen: boolean;
  payment: {
    id: string;
    payment_method: string;
    transaction_id: string | null;
    amount: number;
    status: string;
    note: string | null;
    screenshot_url?: string | null;
  } | null;
  orderId: string;
  onClose: () => void;
  onSaved: () => void;
}

interface PaymentData {
  id: string;
  payment_method: string;
  transaction_id: string | null;
  amount: number;
  status: string;
  note: string | null;
  screenshot_url?: string | null;
}

const PAYMENT_METHODS = ['cod', 'bank_transfer', 'paypal', 'stripe'];
const PAYMENT_STATUSES = ['pending', 'success', 'failed', 'refunded'];

export default function EditPaymentModal({
  isOpen,
  payment,
  orderId,
  onClose,
  onSaved,
}: EditPaymentModalProps) {
  const [paymentMethod, setPaymentMethod] = useState('bank_transfer');
  const [transactionId, setTransactionId] = useState('');
  const [amount, setAmount] = useState('');
  const [status, setStatus] = useState('success');
  const [note, setNote] = useState('');
  const [screenshotPublicId, setScreenshotPublicId] = useState<string | null>(null);
  const [screenshotUrl, setScreenshotUrl] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const currencyCode = useCurrencyStore((s) => s.code);
  const [errors, setErrors] = useState<Record<string, string>>({});

  const prevPaymentRef = useRef<PaymentData | null>(null);

  useEffect(() => {
    if (isOpen && payment && payment.id !== prevPaymentRef.current?.id) {
      prevPaymentRef.current = payment;
      
      const timer = setTimeout(() => {
        setPaymentMethod(payment.payment_method);
        setTransactionId(payment.transaction_id || '');
        setAmount(String(payment.amount));
        setStatus(payment.status);
        setNote(payment.note || '');
        setScreenshotPublicId(payment.screenshot_url || null);
        setScreenshotUrl(payment.screenshot_url || null);
        setErrors({});
      }, 0);
      
      return () => clearTimeout(timer);
    }
    
    if (!isOpen) {
      prevPaymentRef.current = null;
    }
  }, [isOpen, payment]);

  const handleScreenshotUpload = (publicId: string, url: string) => {
    setScreenshotPublicId(publicId);
    setScreenshotUrl(url);
  };

  const handleScreenshotRemove = () => {
    setScreenshotPublicId(null);
    setScreenshotUrl(null);
  };

  const handleSubmit = async () => {
    const newErrors: Record<string, string> = {};
    if (!amount || parseFloat(amount) <= 0) newErrors.amount = 'Valid amount required';
    if (!note.trim()) newErrors.note = 'Note is required';

    if (Object.keys(newErrors).length > 0) {
      setErrors(newErrors);
      return;
    }

    setLoading(true);
    try {
      const formData = new FormData();
      formData.append('payment_method', paymentMethod);
      formData.append('transaction_id', transactionId);
      formData.append('amount', amount);
      formData.append('status', status);
      formData.append('note', note.trim());
      if (screenshotUrl) formData.append('screenshot_url', screenshotUrl);

      const res = await fetch(`/api/orders/${orderId}/payments/${payment?.id}`, {
        method: 'PUT',
        body: formData,
      });

      if (res.ok) {
        toast.success('Payment updated');
        onSaved();
        onClose();
      } else {
        const data = await res.json();
        toast.error(getApiErrorMessage(data, 'Failed to update'));
      }
    } catch {
      toast.error('Network error');
    } finally {
      setLoading(false);
    }
  };

  if (!isOpen || !payment) 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-4" style={{ color: 'var(--color-text)' }}>Edit Payment Record</h3>

        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium mb-1">Method</label>
            <select value={paymentMethod} onChange={(e) => setPaymentMethod(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)' }}>
              {PAYMENT_METHODS.map(m => <option key={m} value={m} className="capitalize">{m.replace(/_/g, ' ')}</option>)}
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium mb-1">Transaction ID</label>
            <input type="text" value={transactionId} onChange={(e) => setTransactionId(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">Status</label>
            <select value={status} onChange={(e) => setStatus(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)' }}>
              {PAYMENT_STATUSES.map(s => <option key={s} value={s} className="capitalize">{s}</option>)}
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium mb-1">Amount ({currencyCode}) <span className="text-red-500">*</span></label>
            <input type="number" value={amount} onChange={(e) => { setAmount(e.target.value); setErrors(p => ({...p, amount: ''})); }}
              className="w-full px-3 py-2 rounded-lg text-sm"
              style={{ background: 'var(--color-surface-alt)', border: errors.amount ? '1px solid var(--color-danger)' : '1px solid var(--color-border)', color: 'var(--color-text)' }} />
            {errors.amount && <p className="text-xs mt-1 text-red-500">{errors.amount}</p>}
          </div>

          {/* Screenshot */}
          <ImageUpload
            value={screenshotPublicId}
            onUpload={handleScreenshotUpload}
            onRemove={handleScreenshotRemove}
            label="Screenshot (Optional)"
            folder="payment-screenshots"
            maxSize={5}
          />

          <div>
            <label className="block text-sm font-medium mb-1">Note <span className="text-red-500">*</span></label>
            <textarea value={note} onChange={(e) => { setNote(e.target.value); setErrors(p => ({...p, note: ''})); }}
              rows={3} className="w-full px-3 py-2 rounded-lg text-sm resize-none"
              style={{ background: 'var(--color-surface-alt)', border: errors.note ? '1px solid var(--color-danger)' : '1px solid var(--color-border)', color: 'var(--color-text)' }} />
            {errors.note && <p className="text-xs mt-1 text-red-500">{errors.note}</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...' : 'Update Payment'}</button>
        </div>
      </div>
    </div>
  );
}