'use client';

import { useState, useEffect, useRef } from 'react';
import ImageUpload from '@/components/ui/ImageUpload';
import { useCurrencyStore } from '@/store/currencyStore';

interface ReturnedItem {
  id: string;
  product_name: string;
  total_price: number;
  variant_name?: string | null;
}

interface PaymentModalProps {
  isOpen: boolean;
  orderNumber: string;
  currentPaymentStatus: string;
  returnedItems: ReturnedItem[];
  onClose: () => void;
  onConfirm: (data: {
    payment_method: string;
    transaction_id: string;
    amount: number;
    status: string;
    note: string;
    item_id?: string | null;
    screenshot_public_id?: string | null;
    screenshot_url?: string | null;
  }) => void;
}

const PAYMENT_METHODS = ['cod', 'bank_transfer', 'paypal', 'stripe'];
const PAYMENT_STATUSES = ['pending', 'success', 'failed', 'refunded'];

export default function PaymentModal({
  isOpen,
  orderNumber,
  currentPaymentStatus,
  returnedItems,
  onClose,
  onConfirm,
}: PaymentModalProps) {
  const [paymentMethod, setPaymentMethod] = useState('bank_transfer');
  const [transactionId, setTransactionId] = useState('');
  const [amount, setAmount] = useState('');
  const [status, setStatus] = useState('success');
  const [note, setNote] = useState('');
  const [selectedItemId, setSelectedItemId] = 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 formatAmount = useCurrencyStore((s) => s.formatAmount);
  const currencyCode = useCurrencyStore((s) => s.code);

  const hasReturnedItems = returnedItems && returnedItems.length > 0;

  const prevIsOpenRef = useRef(false);

  useEffect(() => {
    if (isOpen && !prevIsOpenRef.current) {
      prevIsOpenRef.current = true;
      
      const timer = setTimeout(() => {
        setPaymentMethod('bank_transfer');
        setTransactionId('');
        setAmount('');
        setStatus('success');
        setNote('');
        setSelectedItemId('');
        setScreenshotPublicId(null);
        setScreenshotUrl(null);
        setErrors({});
      }, 0);
      
      return () => clearTimeout(timer);
    }
    
    if (!isOpen) {
      prevIsOpenRef.current = false;
    }
  }, [isOpen]);

  const handleItemSelect = (itemId: string) => {
    setSelectedItemId(itemId);
    const item = returnedItems.find((i) => i.id === itemId);
    if (item) {
      setAmount(String(item.total_price));
      setErrors((prev) => ({ ...prev, amount: '', item: '' }));
    }
  };

  // Handle image upload from ImageUpload component
  const handleScreenshotUpload = (publicId: string, url: string) => {
    setScreenshotPublicId(publicId);
    setScreenshotUrl(url);
    setErrors((prev) => ({ ...prev, screenshot: '' }));
  };

  // Handle image remove
  const handleScreenshotRemove = () => {
    setScreenshotPublicId(null);
    setScreenshotUrl(null);
  };

  const handleSubmit = async () => {
    const newErrors: Record<string, string> = {};

    // Validate
    if (!amount || parseFloat(amount) <= 0) {
      newErrors.amount = 'Valid amount is required';
    }
    if (!note.trim()) {
      newErrors.note = 'Note is required';
    }
    if (status === 'refunded') {
      if (!screenshotPublicId) {
        newErrors.screenshot = 'Screenshot is required for refunds';
      }
      if (hasReturnedItems && !selectedItemId) {
        newErrors.item = 'Select the returned item being refunded';
      }
    }

    if (Object.keys(newErrors).length > 0) {
      setErrors(newErrors);
      return;
    }

    setLoading(true);
    await onConfirm({
      payment_method: paymentMethod,
      transaction_id: transactionId,
      amount: parseFloat(amount),
      status,
      note: note.trim(),
      item_id: selectedItemId || null,
      screenshot_public_id: screenshotPublicId,
      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)' }}>
          Record Payment
        </h3>
        <p className="text-sm mb-4" style={{ color: 'var(--color-text-secondary)' }}>
          Order: <strong>{orderNumber}</strong> | Status:{' '}
          <strong className="capitalize">{currentPaymentStatus}</strong>
        </p>

        <div className="space-y-4">
          {/* Payment Method */}
          <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>

          {/* Transaction ID */}
          <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>

          {/* Status */}
          <div>
            <label
              className="block text-sm font-medium mb-1"
              style={{ color: 'var(--color-text-secondary)' }}
            >
              Status <span className="text-red-500">*</span>
            </label>
            <select
              value={status}
              onChange={(e) => {
                setStatus(e.target.value);
                setErrors({});
              }}
              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>

          {/* Returned Items Dropdown - Only for Refunds */}
          {status === 'refunded' && hasReturnedItems && (
            <div>
              <label
                className="block text-sm font-medium mb-1"
                style={{ color: 'var(--color-text-secondary)' }}
              >
                Returned Item <span className="text-red-500">*</span>
              </label>
              <select
                value={selectedItemId}
                onChange={(e) => handleItemSelect(e.target.value)}
                className="w-full px-3 py-2 rounded-lg text-sm"
                style={{
                  background: 'var(--color-surface-alt)',
                  border: errors.item
                    ? '1px solid var(--color-danger)'
                    : '1px solid var(--color-border)',
                  color: 'var(--color-text)',
                }}
              >
                <option value="">Select returned item...</option>
                {returnedItems.map((item) => (
                  <option key={item.id} value={item.id}>
                    {item.product_name}
                    {item.variant_name ? ` (${item.variant_name})` : ''} - {formatAmount(item.total_price)}
                  </option>
                ))}
              </select>
              {errors.item && (
                <p className="text-xs mt-1" style={{ color: 'var(--color-danger)' }}>
                  {errors.item}
                </p>
              )}
            </div>
          )}

          {/* Amount */}
          <div>
            <label
              className="block text-sm font-medium mb-1"
              style={{ color: 'var(--color-text-secondary)' }}
            >
              Amount ({currencyCode}) <span className="text-red-500">*</span>
            </label>
            <input
              type="number"
              value={amount}
              onChange={(e) => {
                setAmount(e.target.value);
                setErrors((p) => ({ ...p, amount: '' }));
              }}
              placeholder="0.00"
              min="0"
              step="0.01"
              readOnly={status === 'refunded' && !!selectedItemId}
              className="w-full px-3 py-2 rounded-lg text-sm"
              style={{
                background:
                  status === 'refunded' && !!selectedItemId
                    ? 'var(--color-surface)'
                    : 'var(--color-surface-alt)',
                border: errors.amount
                  ? '1px solid var(--color-danger)'
                  : '1px solid var(--color-border)',
                color: 'var(--color-text)',
                cursor:
                  status === 'refunded' && !!selectedItemId ? 'not-allowed' : 'text',
              }}
            />
            {errors.amount && (
              <p className="text-xs mt-1" style={{ color: 'var(--color-danger)' }}>
                {errors.amount}
              </p>
            )}
            {status === 'refunded' && !hasReturnedItems && (
              <p className="text-xs mt-1" style={{ color: 'var(--color-text-tertiary)' }}>
                No returned items found. Enter refund amount manually.
              </p>
            )}
          </div>

          {/* Screenshot Upload - Required for refunds */}
          {status === 'refunded' && (
            <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>
          )}

          {/* Note */}
          <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={
                status === 'refunded'
                  ? 'Refund details - reason, method, reference number (required)...'
                  : 'Payment note (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: status === 'refunded' ? 'var(--color-danger)' : 'var(--color-cta)',
            }}
          >
            {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>
                Saving...
              </span>
            ) : status === 'refunded' ? (
              `Refund ${formatAmount(amount || 0)}`
            ) : (
              'Record Payment'
            )}
          </button>
        </div>
      </div>
    </div>
  );
}