'use client';

import { useState, useEffect } from 'react';
import { TabProps } from '../types';
import Select, { StylesConfig, SingleValue } from 'react-select';

// ─── Types ────────────────────────────────────────────────────────────────────

interface Currency {
  code: string;
  symbol: string;
  name: string;
}

// ─── React-Select Styles ────────────────────────────────────────────────────

const selectStyles: StylesConfig<Currency, false> = {
  control: (base, state) => ({
    ...base,
    background: 'var(--color-surface-alt)',
    border: `1px solid ${state.isFocused ? 'var(--color-cta)' : 'var(--color-border)'}`,
    borderRadius: '0.5rem',
    boxShadow: state.isFocused ? '0 0 0 2px color-mix(in srgb, var(--color-cta) 20%, transparent)' : 'none',
    minHeight: '42px',
    cursor: 'pointer',
    transition: 'all 0.15s',
    '&:hover': { borderColor: 'var(--color-cta)' },
  }),
  valueContainer: (base) => ({ ...base, padding: '2px 12px' }),
  singleValue: (base) => ({ ...base, color: 'var(--color-text)', fontSize: '0.875rem' }),
  placeholder: (base) => ({ ...base, color: 'var(--color-text-tertiary)', fontSize: '0.875rem' }),
  input: (base) => ({ ...base, color: 'var(--color-text)', fontSize: '0.875rem' }),
  menu: (base) => ({
    ...base,
    background: 'var(--color-surface)',
    border: '1px solid var(--color-border)',
    borderRadius: '0.5rem',
    boxShadow: 'var(--shadow-card-md)',
    zIndex: 50,
    overflow: 'hidden',
  }),
  menuList: (base) => ({ ...base, padding: '4px', maxHeight: '200px' }),
  option: (base, state) => ({
    ...base,
    background: state.isSelected
      ? 'var(--color-cta)'
      : state.isFocused
      ? 'color-mix(in srgb, var(--color-cta) 10%, transparent)'
      : 'transparent',
    color: state.isSelected ? 'white' : 'var(--color-text)',
    fontSize: '0.875rem',
    borderRadius: '0.375rem',
    cursor: 'pointer',
    padding: '8px 12px',
    '&:active': { background: 'color-mix(in srgb, var(--color-cta) 20%, transparent)' },
  }),
  noOptionsMessage: (base) => ({ ...base, color: 'var(--color-text-secondary)', fontSize: '0.875rem' }),
  dropdownIndicator: (base) => ({
    ...base,
    color: 'var(--color-text-tertiary)',
    padding: '0 8px',
    '&:hover': { color: 'var(--color-text)' },
  }),
  indicatorSeparator: (base) => ({ ...base, background: 'var(--color-border)' }),
};

// ─── Component ─────────────────────────────────────────────────────────────

export function OrderTab({ data, onChange, onArrayToggle, canUpdate }: TabProps) {
  const [currencies, setCurrencies] = useState<Currency[]>([]);
  const [loadingCurrencies, setLoadingCurrencies] = useState(true);

  const paymentMethods = ['cod', 'bank_transfer', 'paypal', 'stripe'];
  const methodLabels: Record<string, string> = {
    cod: 'Cash on Delivery',
    bank_transfer: 'Bank Transfer',
    paypal: 'PayPal',
    stripe: 'Stripe'
  };

  const methodIcons: Record<string, string> = {
    cod: '💵',
    bank_transfer: '🏦',
    paypal: '💳',
    stripe: '⚡'
  };

  // ─── Fetch Currencies ─────────────────────────────────────────────────────

  useEffect(() => {
    async function loadCurrencies() {
      try {
        const baseUrl = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000';
        const res = await fetch(`${baseUrl}/api/currencies`, {
          cache: 'no-store',
        });

        if (!res.ok) {
          throw new Error('Failed to fetch currencies');
        }

        const result = await res.json();
        setCurrencies(result.data || []);
      } catch (error) {
        console.error('Failed to load currencies:', error);
        // Set fallback currencies
        setCurrencies([
          { code: 'USD', symbol: '$', name: 'US Dollar' },
          { code: 'EUR', symbol: '€', name: 'Euro' },
          { code: 'GBP', symbol: '£', name: 'British Pound' },
          { code: 'PKR', symbol: '₨', name: 'Pakistani Rupee' },
          { code: 'INR', symbol: '₹', name: 'Indian Rupee' },
        ]);
      } finally {
        setLoadingCurrencies(false);
      }
    }

    loadCurrencies();
  }, []);

  // ─── Currency Select Handlers ────────────────────────────────────────────

  const selectedCurrency = currencies.find(c => c.code === data.default_currency);

  const handleCurrencyChange = (option: SingleValue<Currency>) => {
    onChange('default_currency', option?.code || 'USD');
  };

  // ─── Custom Option Format ────────────────────────────────────────────────

  const formatOptionLabel = ({ code, symbol, name }: Currency) => (
    <div className="flex items-center gap-2">
      <span className="font-medium">{code}</span>
      <span className="text-sm" style={{ color: 'var(--color-text-tertiary)' }}>
        {symbol} - {name}
      </span>
    </div>
  );

  return (
    <div className="space-y-6">
      {/* Order Amount Settings */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div>
          <label className="block text-sm font-medium mb-1.5" style={{ color: 'var(--color-text-secondary)' }}>
            Default Currency
          </label>
          {loadingCurrencies ? (
            <div 
              className="w-full px-4 py-2.5 rounded-lg text-sm animate-pulse"
              style={{
                background: 'var(--color-surface-alt)',
                border: '1px solid var(--color-border)',
                height: '42px',
              }}
            />
          ) : (
            <Select<Currency, false>
              instanceId="currency-select"
              options={currencies}
              value={selectedCurrency}
              onChange={handleCurrencyChange}
              placeholder="Select default currency..."
              isSearchable
              isClearable={false}
              isDisabled={!canUpdate}
              formatOptionLabel={formatOptionLabel}
              styles={selectStyles}
              getOptionLabel={(option) => `${option.code} - ${option.name}`}
              getOptionValue={(option) => option.code}
              noOptionsMessage={() => 'No currencies found'}
            />
          )}
          <p className="text-xs mt-1" style={{ color: 'var(--color-text-tertiary)' }}>
            Default currency used for all prices and transactions
          </p>
        </div>

        <div>
          <label className="block text-sm font-medium mb-1.5" style={{ color: 'var(--color-text-secondary)' }}>
            Currency Display Format
          </label>
          <select
            value={data.currency_display_format || 'symbol'}
            onChange={(e) => onChange('currency_display_format', e.target.value)}
            disabled={!canUpdate}
            className="w-full px-4 py-2.5 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20 disabled:opacity-50"
            style={{
              background: 'var(--color-surface-alt)',
              border: '1px solid var(--color-border)',
              color: 'var(--color-text)',
            }}
          >
            <option value="symbol">Symbol ({selectedCurrency?.symbol || '$'})</option>
            <option value="code">Code ({selectedCurrency?.code || 'USD'})</option>
            <option value="both">Both ({selectedCurrency?.symbol || '$'} {selectedCurrency?.code || 'USD'})</option>
          </select>
          <p className="text-xs mt-1" style={{ color: 'var(--color-text-tertiary)' }}>
            How currency should be displayed across the store
          </p>
        </div>

        <div>
          <label className="block text-sm font-medium mb-1.5" style={{ color: 'var(--color-text-secondary)' }}>
            Minimum Order Amount
          </label>
          <div className="relative">
            <span className="absolute left-3 top-1/2 -translate-y-1/2 text-sm" style={{ color: 'var(--color-text-tertiary)' }}>
              {selectedCurrency?.symbol || '$'}
            </span>
            <input
              type="number"
              step="0.01"
              min="0"
              value={data.min_order_amount ?? 0}
              onChange={(e) => onChange('min_order_amount', e.target.value)}
              disabled={!canUpdate}
              placeholder="0.00"
              className="w-full pl-8 pr-4 py-2.5 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20 disabled:opacity-50"
              style={{
                background: 'var(--color-surface-alt)',
                border: '1px solid var(--color-border)',
                color: 'var(--color-text)',
              }}
            />
          </div>
          <p className="text-xs mt-1" style={{ color: 'var(--color-text-tertiary)' }}>
            Minimum amount required to place an order. Set 0 for no minimum.
          </p>
        </div>

        <div>
          <label className="block text-sm font-medium mb-1.5" style={{ color: 'var(--color-text-secondary)' }}>
            VAT / GST Percentage
          </label>
          <div className="relative">
            <span className="absolute right-3 top-1/2 -translate-y-1/2 text-sm" style={{ color: 'var(--color-text-tertiary)' }}>
              %
            </span>
            <input
              type="number"
              step="0.01"
              min="0"
              max="100"
              value={data.vat_percentage ?? 0}
              onChange={(e) => onChange('vat_percentage', e.target.value)}
              disabled={!canUpdate}
              placeholder="0.00"
              className="w-full px-4 pr-8 py-2.5 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20 disabled:opacity-50"
              style={{
                background: 'var(--color-surface-alt)',
                border: '1px solid var(--color-border)',
                color: 'var(--color-text)',
              }}
            />
          </div>
          <p className="text-xs mt-1" style={{ color: 'var(--color-text-tertiary)' }}>
            Tax percentage applied to all orders
          </p>
        </div>

        <div>
          <label className="block text-sm font-medium mb-1.5" style={{ color: 'var(--color-text-secondary)' }}>
            VAT / GST Label
          </label>
          <input
            type="text"
            value={data.vat_label || 'GST'}
            onChange={(e) => onChange('vat_label', e.target.value)}
            disabled={!canUpdate}
            placeholder="GST"
            className="w-full px-4 py-2.5 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20 disabled:opacity-50"
            style={{
              background: 'var(--color-surface-alt)',
              border: '1px solid var(--color-border)',
              color: 'var(--color-text)',
            }}
          />
          <p className="text-xs mt-1" style={{ color: 'var(--color-text-tertiary)' }}>
            What to call the tax (e.g., GST, VAT, Sales Tax)
          </p>
        </div>
      </div>

      {/* Payment Methods */}
      <div>
        <label className="block text-sm font-medium mb-3" style={{ color: 'var(--color-text-secondary)' }}>
          Enabled Payment Methods
        </label>
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
          {paymentMethods.map((method) => {
            const isChecked = (data.enabled_payment_methods || []).includes(method as any);
            return (
              <label 
                key={method} 
                className="flex items-center gap-3 p-3 rounded-lg cursor-pointer transition-all hover:scale-[1.02]"
                style={{
                  background: isChecked ? 'var(--color-cta-light)' : 'var(--color-surface-alt)',
                  border: `2px solid ${isChecked ? 'var(--color-cta)' : 'var(--color-border)'}`,
                }}
              >
                <input
                  type="checkbox"
                  checked={isChecked}
                  onChange={() => onArrayToggle('enabled_payment_methods', method)}
                  disabled={!canUpdate}
                  className="w-4 h-4 rounded"
                  style={{ accentColor: 'var(--color-cta)' }}
                />
                <span className="text-lg">{methodIcons[method]}</span>
                <span className="text-sm font-medium" style={{ color: 'var(--color-text)' }}>
                  {methodLabels[method] || method}
                </span>
                {isChecked && (
                  <span className="ml-auto text-xs px-2 py-0.5 rounded-full" style={{
                    background: 'var(--color-success)',
                    color: 'white'
                  }}>
                    Active
                  </span>
                )}
              </label>
            );
          })}
        </div>
        <p className="text-xs mt-2" style={{ color: 'var(--color-text-tertiary)' }}>
          Select which payment methods customers can use during checkout
        </p>
      </div>

      {/* Guest Checkout */}
      <div>
        <div className="flex items-center gap-3 p-4 rounded-lg border" style={{ 
          borderColor: 'var(--color-border)',
          background: 'var(--color-surface-alt)'
        }}>
          <label className="relative inline-flex items-center cursor-pointer">
            <input
              type="checkbox"
              checked={data.enable_guest_checkout ?? true}
              onChange={() => {
                const currentValue = data.enable_guest_checkout ?? true;
                onChange('enable_guest_checkout', !currentValue);
              }}
              disabled={!canUpdate}
              className="sr-only peer"
            />
            <div className="w-11 h-6 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-0.5 after:left-0.5 after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-cta" style={{
              background: data.enable_guest_checkout ? 'var(--color-cta)' : 'var(--color-border)',
            }}></div>
            <span className="ml-3 text-sm font-medium" style={{ color: 'var(--color-text)' }}>
              {data.enable_guest_checkout ? '✅ Enabled' : '❌ Disabled'}
            </span>
          </label>
        </div>
        <div className="mt-2 p-3 rounded-lg" style={{
          background: 'var(--color-surface-alt)',
          border: '1px solid var(--color-border)'
        }}>
          <p className="text-xs" style={{ color: 'var(--color-text-tertiary)' }}>
            <strong>Guest Checkout:</strong> Allow customers to checkout without creating an account. 
            This can increase conversion rates but may reduce customer retention.
          </p>
        </div>
      </div>

      {/* Refund Policy */}
      <div>
        <label className="block text-sm font-medium mb-3" style={{ color: 'var(--color-text-secondary)' }}>
          Refund Policy
        </label>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
          <div className="flex items-center gap-3 p-4 rounded-lg border" style={{
            borderColor: 'var(--color-border)',
            background: 'var(--color-surface-alt)',
          }}>
            <label className="relative inline-flex items-center cursor-pointer">
              <input
                type="checkbox"
                checked={data.refund_include_tax ?? true}
                onChange={() => onChange('refund_include_tax', !(data.refund_include_tax ?? true))}
                disabled={!canUpdate}
                className="sr-only peer"
              />
              <div className="w-11 h-6 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-0.5 after:left-0.5 after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-cta" style={{
                background: data.refund_include_tax ? 'var(--color-cta)' : 'var(--color-border)',
              }}></div>
              <span className="ml-3 text-sm font-medium" style={{ color: 'var(--color-text)' }}>
                Refund {data.vat_label || 'GST'} / tax
              </span>
            </label>
          </div>

          <div className="flex items-center gap-3 p-4 rounded-lg border" style={{
            borderColor: 'var(--color-border)',
            background: 'var(--color-surface-alt)',
          }}>
            <label className="relative inline-flex items-center cursor-pointer">
              <input
                type="checkbox"
                checked={data.refund_include_delivery_fee ?? true}
                onChange={() => onChange('refund_include_delivery_fee', !(data.refund_include_delivery_fee ?? true))}
                disabled={!canUpdate}
                className="sr-only peer"
              />
              <div className="w-11 h-6 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-0.5 after:left-0.5 after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-cta" style={{
                background: data.refund_include_delivery_fee ? 'var(--color-cta)' : 'var(--color-border)',
              }}></div>
              <span className="ml-3 text-sm font-medium" style={{ color: 'var(--color-text)' }}>
                Refund delivery fee
              </span>
            </label>
          </div>
        </div>
        <div className="mt-2 p-3 rounded-lg" style={{
          background: 'var(--color-surface-alt)',
          border: '1px solid var(--color-border)',
        }}>
          <p className="text-xs" style={{ color: 'var(--color-text-tertiary)' }}>
            <strong>Refund {data.vat_label || 'GST'} / tax:</strong> when on, a full refund includes the tax the customer
            paid, and a partial (single-item) refund includes that item&apos;s proportional share of the tax. When off,
            only the item/order amount is refunded, never the tax. <strong>Refund delivery fee:</strong> only applies
            when the <em>entire</em> order is refunded (a single-item partial refund never refunds delivery, regardless
            of this setting).
          </p>
        </div>
      </div>

      {/* Summary Card */}
      <div className="p-4 rounded-lg" style={{ 
        background: 'var(--color-surface-alt)',
        border: '1px solid var(--color-border)'
      }}>
        <h4 className="text-sm font-medium mb-2" style={{ color: 'var(--color-text-secondary)' }}>
          Order Settings Summary
        </h4>
        <div className="grid grid-cols-2 gap-2 text-xs">
          <div>
            <span style={{ color: 'var(--color-text-tertiary)' }}>Default Currency:</span>
            <span className="ml-1 font-medium" style={{ color: 'var(--color-text)' }}>
              {selectedCurrency?.symbol || '$'} {selectedCurrency?.code || 'USD'}
            </span>
          </div>
          <div>
            <span style={{ color: 'var(--color-text-tertiary)' }}>Display Format:</span>
            <span className="ml-1 font-medium" style={{ color: 'var(--color-text)' }}>
              {data.currency_display_format || 'symbol'}
            </span>
          </div>
          <div>
            <span style={{ color: 'var(--color-text-tertiary)' }}>Min Order:</span>
            <span className="ml-1 font-medium" style={{ color: 'var(--color-text)' }}>
              {selectedCurrency?.symbol || '$'}{data.min_order_amount ?? 0}
            </span>
          </div>
          <div>
            <span style={{ color: 'var(--color-text-tertiary)' }}>VAT Rate:</span>
            <span className="ml-1 font-medium" style={{ color: 'var(--color-text)' }}>
              {data.vat_percentage ?? 0}%
            </span>
          </div>
          <div>
            <span style={{ color: 'var(--color-text-tertiary)' }}>VAT Label:</span>
            <span className="ml-1 font-medium" style={{ color: 'var(--color-text)' }}>
              {data.vat_label || 'GST'}
            </span>
          </div>
          <div>
            <span style={{ color: 'var(--color-text-tertiary)' }}>Payment Methods:</span>
            <span className="ml-1 font-medium" style={{ color: 'var(--color-text)' }}>
              {(data.enabled_payment_methods || []).length} enabled
            </span>
          </div>
          <div className="col-span-2">
            <span style={{ color: 'var(--color-text-tertiary)' }}>Guest Checkout:</span>
            <span className="ml-1 font-medium" style={{ 
              color: data.enable_guest_checkout ? 'var(--color-success)' : 'var(--color-danger)'
            }}>
              {data.enable_guest_checkout ? 'Enabled' : 'Disabled'}
            </span>
          </div>
        </div>
      </div>
    </div>
  );
}