import { useState } from 'react';
import PriceSparkline from './PriceSparkline';

export interface WatchlistItem {
  id: number;
  product_id: number;
  target_price: number | null;
  notify_price_drop: boolean;
  notify_back_in_stock: boolean;
  notify_push_price_drop: boolean;
  notify_push_back_in_stock: boolean;
  size_override: string | null;
  name: string;
  brand: string;
  slug: string;
  image_url: string;
  cutout_image_url: string | null;
  colorway: string;
  lowest_price: number | null;
  shop_count: number;
  original_price: number | null;
  price_7d_ago: number | null;
  sparkline: number[];
}

interface Props {
  item: WatchlistItem;
  onRemove: (productId: number) => void;
  onUpdateTargetPrice: (productId: number, price: number | null) => void;
  onToggleNotification: (productId: number, field: 'notify_price_drop' | 'notify_back_in_stock' | 'notify_push_price_drop' | 'notify_push_back_in_stock', value: boolean) => void;
  pushEnabled: boolean;
  onEnablePush: () => void;
  onUpdateSizeOverride?: (productId: number, size: string | null) => void;
}

const EU_SIZES = ['36', '37', '37.5', '38', '38.5', '39', '40', '40.5', '41', '42', '42.5', '43', '44', '44.5', '45', '46', '47', '48'];

export default function WatchlistItemCard({ item, onRemove, onUpdateTargetPrice, onToggleNotification, onUpdateSizeOverride, pushEnabled, onEnablePush }: Props) {
  const [editingPrice, setEditingPrice] = useState(false);
  const [priceInput, setPriceInput] = useState('');
  const [editingSize, setEditingSize] = useState(false);

  const lowestPrice = item.lowest_price ? parseFloat(String(item.lowest_price)) : null;
  const targetPrice = item.target_price ? parseFloat(String(item.target_price)) : null;
  const originalPrice = item.original_price ? parseFloat(String(item.original_price)) : null;
  const hasDiscount = originalPrice && lowestPrice && lowestPrice < originalPrice;
  const price7dAgo = item.price_7d_ago ? parseFloat(String(item.price_7d_ago)) : null;
  const priceDelta = (lowestPrice && price7dAgo) ? lowestPrice - price7dAgo : null;

  // Status calculation
  let statusLabel = '';
  let statusClass = '';
  if (targetPrice && lowestPrice) {
    if (lowestPrice <= targetPrice) {
      statusLabel = 'Deal gevonden!';
      statusClass = 'bg-green-500/15 text-green-400';
    } else if (lowestPrice <= targetPrice * 1.1) {
      statusLabel = 'Bijna!';
      statusClass = 'bg-yellow-500/15 text-yellow-400';
    } else {
      statusLabel = 'Wachten';
      statusClass = 'bg-text-muted/10 text-text-muted';
    }
  }

  const handleSavePrice = () => {
    const price = priceInput ? parseFloat(priceInput) : null;
    onUpdateTargetPrice(item.product_id, price);
    setEditingPrice(false);
  };

  const handleSaveSize = (newSize: string | null) => {
    if (onUpdateSizeOverride) {
      onUpdateSizeOverride(item.product_id, newSize);
    }
    setEditingSize(false);
    setPriceInput('');
  };

  return (
    <div className="rounded-xl border border-border/30 bg-bg-card p-4">
      <div className="flex gap-4">
        <a href={`/sneakers/${item.slug}`} className="shrink-0">
          <img
            src={`/api/img/${item.product_id}`}
            alt={item.name}
            className="h-20 w-20 rounded-lg object-contain bg-white sm:h-24 sm:w-24"
            onError={(e) => {
              (e.target as HTMLImageElement).src = '/img/sneaker-placeholder.svg';
            }}
          />
        </a>
        <div className="flex-1 min-w-0">
          <div className="flex items-start justify-between gap-2">
            <div>
              <p className="text-[11px] font-bold uppercase tracking-widest text-text-muted">{item.brand}</p>
              <a href={`/sneakers/${item.slug}`} className="font-semibold text-text hover:text-accent transition-colors line-clamp-1">
                {item.name}
              </a>
            </div>
            {statusLabel && (
              <span className={`shrink-0 rounded-full px-2 py-0.5 text-[10px] font-bold ${statusClass}`}>
                {statusLabel}
              </span>
            )}
          </div>
          {item.colorway && <p className="text-xs text-text-muted">{item.colorway}</p>}

          <div className="mt-2 flex flex-wrap items-center gap-3">
            {lowestPrice ? (
              <span className="text-lg font-black text-accent">
                &euro;{lowestPrice.toFixed(2).replace('.', ',')}
              </span>
            ) : (
              <span className="text-sm text-text-muted">Niet beschikbaar</span>
            )}
            {item.sparkline.length >= 2 && (
              <PriceSparkline data={item.sparkline} className="hidden sm:block" />
            )}
            {hasDiscount && (
              <span className="text-sm text-text-muted line-through">
                &euro;{originalPrice!.toFixed(2).replace('.', ',')}
              </span>
            )}
            <span className="text-xs text-text-muted">{item.shop_count} shop{Number(item.shop_count) !== 1 ? 's' : ''}</span>
            {priceDelta !== null && priceDelta !== 0 && (
              <span className={`flex items-center gap-0.5 text-xs font-semibold ${priceDelta < 0 ? 'text-green-400' : 'text-red-400'}`}>
                {priceDelta < 0 ? (
                  <svg className="h-3 w-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={3}><path strokeLinecap="round" strokeLinejoin="round" d="M19 14l-7 7m0 0l-7-7m7 7V3" /></svg>
                ) : (
                  <svg className="h-3 w-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={3}><path strokeLinecap="round" strokeLinejoin="round" d="M5 10l7-7m0 0l7 7m-7-7v18" /></svg>
                )}
                {priceDelta < 0 ? '-' : '+'}&euro;{Math.abs(priceDelta).toFixed(2).replace('.', ',')} deze week
              </span>
            )}
          </div>

          {/* Target price */}
          <div className="mt-2 flex items-center gap-2">
            {editingPrice ? (
              <>
                <span className="text-xs text-text-muted">Alert onder &euro;</span>
                <input
                  type="number"
                  value={priceInput}
                  onChange={e => setPriceInput(e.target.value)}
                  step="0.01"
                  min="0"
                  className="w-20 rounded border border-border/30 bg-bg-elevated px-2 py-1 text-sm text-text focus:border-accent/50 focus:outline-none"
                  autoFocus
                  onKeyDown={e => e.key === 'Enter' && handleSavePrice()}
                />
                <button onClick={handleSavePrice} className="text-xs text-accent hover:underline">Opslaan</button>
                <button onClick={() => setEditingPrice(false)} className="text-xs text-text-muted hover:text-text">Annuleren</button>
              </>
            ) : (
              <button
                onClick={() => { setEditingPrice(true); setPriceInput(targetPrice?.toString() || ''); }}
                className="text-xs text-text-secondary hover:text-accent transition-colors"
              >
                {targetPrice
                  ? `Alert onder \u20AC${targetPrice.toFixed(2).replace('.', ',')} \u2014 wijzig`
                  : '+ Prijsalert instellen'}
              </button>
            )}
          </div>

          {/* Size override */}
          <div className="mt-2 flex items-center gap-2">
            {editingSize ? (
              <>
                <span className="text-xs text-text-muted">Maat:</span>
                <select
                  defaultValue={item.size_override || ''}
                  onChange={e => handleSaveSize(e.target.value || null)}
                  className="rounded border border-border/30 bg-bg-elevated px-2 py-1 text-xs text-text focus:border-accent/50 focus:outline-none"
                  autoFocus
                >
                  <option value="">Gebruik profiel</option>
                  {EU_SIZES.map(s => (
                    <option key={s} value={s}>EU {s}</option>
                  ))}
                </select>
                <button onClick={() => setEditingSize(false)} className="text-xs text-text-muted hover:text-text">Klaar</button>
              </>
            ) : (
              <button
                onClick={() => setEditingSize(true)}
                className="text-xs text-text-secondary hover:text-accent transition-colors"
              >
                Maat: {item.size_override ? `EU ${item.size_override}` : 'Profiel'} • wijzig
              </button>
            )}
          </div>
        </div>

        <button
          onClick={() => onRemove(item.product_id)}
          className="shrink-0 self-start rounded-full p-2 text-text-muted hover:bg-red-500/10 hover:text-red-400 transition-colors"
          title="Verwijderen"
        >
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" className="w-4 h-4">
            <path d="M6.28 5.22a.75.75 0 00-1.06 1.06L8.94 10l-3.72 3.72a.75.75 0 101.06 1.06L10 11.06l3.72 3.72a.75.75 0 101.06-1.06L11.06 10l3.72-3.72a.75.75 0 00-1.06-1.06L10 8.94 6.28 5.22z" />
          </svg>
        </button>
      </div>

      {/* Notification toggles */}
      <div className="mt-3 space-y-2 border-t border-border/20 pt-3">
        {/* Email row */}
        <div className="flex flex-wrap items-center gap-3">
          <span className="w-8 text-[10px] font-semibold uppercase tracking-wider text-text-muted">Email</span>
          <label className="flex items-center gap-2 cursor-pointer">
            <button
              onClick={() => onToggleNotification(item.product_id, 'notify_price_drop', !item.notify_price_drop)}
              className={`h-5 w-9 shrink-0 rounded-full p-0.5 transition-colors ${item.notify_price_drop ? 'bg-accent' : 'bg-border/50'}`}
            >
              <div className={`h-4 w-4 rounded-full bg-white transition-transform ${item.notify_price_drop ? 'translate-x-4' : 'translate-x-0'}`} />
            </button>
            <span className="text-xs text-text-muted">Prijsdaling</span>
          </label>
          {Number(item.shop_count) === 0 && (
            <label className="flex items-center gap-2 cursor-pointer">
              <button
                onClick={() => onToggleNotification(item.product_id, 'notify_back_in_stock', !item.notify_back_in_stock)}
                className={`h-5 w-9 shrink-0 rounded-full p-0.5 transition-colors ${item.notify_back_in_stock ? 'bg-accent' : 'bg-border/50'}`}
              >
                <div className={`h-4 w-4 rounded-full bg-white transition-transform ${item.notify_back_in_stock ? 'translate-x-4' : 'translate-x-0'}`} />
              </button>
              <span className="text-xs text-text-muted">Weer op voorraad</span>
            </label>
          )}
        </div>
        {/* Push row */}
        <div className="flex flex-wrap items-center gap-3">
          <span className="w-8 text-[10px] font-semibold uppercase tracking-wider text-text-muted">Push</span>
          {pushEnabled ? (
            <>
              <label className="flex items-center gap-2 cursor-pointer">
                <button
                  onClick={() => onToggleNotification(item.product_id, 'notify_push_price_drop', !item.notify_push_price_drop)}
                  className={`h-5 w-9 shrink-0 rounded-full p-0.5 transition-colors ${item.notify_push_price_drop ? 'bg-accent' : 'bg-border/50'}`}
                >
                  <div className={`h-4 w-4 rounded-full bg-white transition-transform ${item.notify_push_price_drop ? 'translate-x-4' : 'translate-x-0'}`} />
                </button>
                <span className="text-xs text-text-muted">Prijsdaling</span>
              </label>
              {Number(item.shop_count) === 0 && (
                <label className="flex items-center gap-2 cursor-pointer">
                  <button
                    onClick={() => onToggleNotification(item.product_id, 'notify_push_back_in_stock', !item.notify_push_back_in_stock)}
                    className={`h-5 w-9 shrink-0 rounded-full p-0.5 transition-colors ${item.notify_push_back_in_stock ? 'bg-accent' : 'bg-border/50'}`}
                  >
                    <div className={`h-4 w-4 rounded-full bg-white transition-transform ${item.notify_push_back_in_stock ? 'translate-x-4' : 'translate-x-0'}`} />
                  </button>
                  <span className="text-xs text-text-muted">Weer op voorraad</span>
                </label>
              )}
            </>
          ) : (
            <button
              onClick={onEnablePush}
              className="flex items-center gap-1.5 text-xs text-text-muted hover:text-accent transition-colors"
            >
              <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9"/><path d="M10.3 21a1.94 1.94 0 0 0 3.4 0"/></svg>
              Push inschakelen
            </button>
          )}
        </div>
      </div>
    </div>
  );
}
