'use client';

import { useState, useEffect, useRef } from 'react';
import ImageUpload from '@/components/ui/ImageUpload';

interface RefundFullOrderModalProps {
  isOpen: boolean;
  orderNumber: string;
  itemCount: number;
  onClose: () => void;
  onConfirm: (data: {
    payment_method: string;
    transaction_id: string;
    note: string;
    screenshot_url: string;
  }) => void;
}

const PAYMENT_METHODS = ['cod', 'bank_transfer', 'paypal', 'stripe'];

// One-click counterpart to refunding each returned item individually via
// PaymentModal — shown only once every item on the order has been
// returned (see OrderDetailModal's "Refund Full Order" button). No amount
// field: the server computes the real, tax/coupon-aware total from
// computeItemRefundAmount() (src/lib/orders/refundCalculations.ts) — the
// same calculation the per-item flow already uses — so nothing here can
// drift from what refunding the same items one at a time would total.
export default function RefundFullOrderModal({
  isOpen,
  orderNumber,
  itemCount,
  onClose,
  onConfirm,
}: RefundFullOrderModalProps) {
  const [paymentMethod, setPaymentMethod] = useState('bank_transfer');
  const [transactionId, setTransactionId] = useState('');
  const [note, setNote] = useState('');
  const [screenshotPublicId, setScreenshotPublicId] = useState<string | null>(null);
  const [screenshotUrl, setScreenshotUrl] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [errors, setErrors] = useState<Record<string, string>>({});

  const prevIsOpenRef = useRef(false);

  useEffect(() => {
    if (isOpen && !prevIsOpenRef.current) {
      prevIsOpenRef.current = true;
      const timer = setTimeout(() => {
        setPaymentMethod('bank_transfer');
        setTransactionId('');
        setNote('');
        setScreenshotPublicId(null);
        setScreenshotUrl(null);
        setErrors({});
      }, 0);
      return () => clearTimeout(timer);
    }
    if (!isOpen) {
      prevIsOpenRef.current = false;
    }
  }, [isOpen]);

  const handleScreenshotUpload = (publicId: string, url: string) => {
    setScreenshotPublicId(publicId);
    setScreenshotUrl(url);
    setErrors((prev) => ({ ...prev, screenshot: '' }));
  };

  const handleScreenshotRemove = () => {
    setScreenshotPublicId(null);
    setScreenshotUrl(null);
  };

  const handleSubmit = async () => {
    const newErrors: Record<string, string> = {};
    if (!note.trim()) newErrors.note = 'Note is required';
    if (!screenshotUrl) newErrors.screenshot = 'Screenshot is required for refunds';

    if (Object.keys(newErrors).length > 0) {
      setErrors(newErrors);
      return;
    }

    setLoading(true);
    await onConfirm({
      payment_method: paymentMethod,
      transaction_id: transactionId,
      note: note.trim(),
      screenshot_url: screenshotUrl!,
    });
    setLoading(false);
  };

  if (!isOpen) return null;

  return (
    <div
      className="fixed inset-0 z-50 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-2" style={{ color: 'var(--color-text)' }}>
          Refund Full Order
        </h3>
        <p className="text-sm mb-4" style={{ color: 'var(--color-text-secondary)' }}>
          Order: <strong>{orderNumber}</strong> — refunding all {itemCount} returned item{itemCount === 1 ? '' : 's'}
        </p>
        <p
          className="text-xs mb-4 p-2 rounded"
          style={{ background: 'var(--color-surface-alt)', color: 'var(--color-text-tertiary)' }}
        >
          The refund amount is calculated automatically (item price, proportional tax and coupon share per item, plus delivery fee where the refund policy includes it) and shown once submitted.
        </p>

        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium mb-1" style={{ color: 'var(--color-text-secondary)' }}>
              Method <span className="text-red-500">*</span>
            </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" style={{ color: 'var(--color-text-secondary)' }}>
              Transaction ID
            </label>
            <input
              type="text"
              value={transactionId}
              onChange={(e) => setTransactionId(e.target.value)}
              placeholder="e.g., TXN-123456"
              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>

          <ImageUpload
            value={screenshotPublicId}
            onUpload={handleScreenshotUpload}
            onRemove={handleScreenshotRemove}
            label="Refund Screenshot"
            folder="payment-screenshots"
            maxSize={5}
            accept="image/jpeg,image/png,image/webp"
            aspectRatio={16 / 9}
          />
          {errors.screenshot && (
            <p className="text-xs -mt-2" style={{ color: 'var(--color-danger)' }}>
              {errors.screenshot}
            </p>
          )}

          <div>
            <label className="block text-sm font-medium mb-1" style={{ color: 'var(--color-text-secondary)' }}>
              Note <span className="text-red-500">*</span>
            </label>
            <textarea
              value={note}
              onChange={(e) => {
                setNote(e.target.value);
                setErrors((p) => ({ ...p, note: '' }));
              }}
              placeholder="Refund details - reason, method, reference number (required)..."
              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" style={{ color: 'var(--color-danger)' }}>
                {errors.note}
              </p>
            )}
          </div>
        </div>

        <div className="flex gap-3 justify-end mt-6">
          <button
            onClick={onClose}
            disabled={loading}
            className="px-4 py-2 rounded-lg text-sm font-medium transition-all hover:opacity-80"
            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 font-medium text-white transition-all hover:opacity-90 disabled:opacity-50"
            style={{ background: 'var(--color-danger)' }}
          >
            {loading ? (
              <span className="flex items-center gap-2">
                <svg className="animate-spin h-4 w-4" viewBox="0 0 24 24">
                  <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none" />
                  <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
                </svg>
                Processing...
              </span>
            ) : (
              'Refund Full Order'
            )}
          </button>
        </div>
      </div>
    </div>
  );
}
