'use client';

import { useState, useEffect, useCallback, useMemo } from 'react';
import useSWR, { mutate } from 'swr';
import { useApi } from '@/lib/useApi';
import { useParams, useRouter } from 'next/navigation';
import { SetPageHeader } from '@/components/layout/SetPageHeader';
import { Card, Button, Icon, Pill } from '@/components/ui';
import {
  getShoppingList,
  addShoppingItem,
  updateShoppingItem,
  removeShoppingItem,
  syncToPantry,
  getBasketStoreComparison,
  updateShoppingList,
} from '@/services/shopping-lists';
import { listProducts } from '@/services/products';
import { useShoppingListSync } from '@/lib/useShoppingListSync';

export default function ShoppingListDetailsPage() {
  const { householdId, isLoading: isAuthLoading } = useApi();
  const { id: listId } = useParams() as { id: string };
  const router = useRouter();

  const [error, setError] = useState('');
  const [storeOptions, setStoreOptions] = useState<any[]>([]);
  const [isStoreLoading, setIsStoreLoading] = useState(false);
  const [products, setProducts] = useState<any[]>([]);
  const [selectedProductId, setSelectedProductId] = useState('');
  const [customItemName, setCustomItemName] = useState('');
  const [qty, setQty] = useState(1);
  const [unit, setUnit] = useState('g');
  const [notes, setNotes] = useState('');
  const [isAdding, setIsAdding] = useState(false);

  // Load core list context
  const swrKey = householdId && listId ? `shopping-list-${householdId}-${listId}` : null;
  const { data: list, mutate: mutateList, isLoading: listLoading, error: listError } = useSWR(
    swrKey,
    () => getShoppingList(householdId!, listId)
  );

  useEffect(() => {
    if (listError) setError(listError.message || 'Shopping list not found');
  }, [listError]);

  // Run price comparisons
  const fetchComparisons = useCallback(async () => {
    if (!householdId || !listId) return;
    setIsStoreLoading(true);
    try {
      const comparison = await getBasketStoreComparison(householdId, listId);
      setStoreOptions(comparison.singleStoreOptions || []);
    } catch (err) {
      console.error('Comparison load fail', err);
    } finally {
      setIsStoreLoading(false);
    }
  }, [householdId, listId]);

  // Pre-load household products for predictive inputs
  useEffect(() => {
    if (!householdId) return;
    listProducts(householdId).then(res => setProducts(res.data)).catch(console.error);
  }, [householdId]);

  // Handle WS Remote Event Broadcasts
  const handleRemoteSync = useCallback((msg: any) => {
    console.log('🔔 Remote state delta payload:', msg);
    mutateList(); // Revalidate with server on remote changes
  }, [mutateList]);

  // Inject Real-Time Hooks
  const { isConnected, toggleItemCheck } = useShoppingListSync(
    householdId || '',
    listId,
    handleRemoteSync
  );

  // 1. Perform Live Interactivity (Toggle Checks)
  const handleToggleCheck = async (itemId: string, currentChecked: boolean) => {
    const nextChecked = !currentChecked;
    
    // Optimistic Client Update
    mutateList(async (prev: any) => ({
      ...prev,
      items: prev.items.map((it: any) => it.id === itemId ? { ...it, checked: nextChecked } : it)
    }), { revalidate: false });

    // Emit to WS Channel
    toggleItemCheck(itemId, nextChecked);

    // Persist standard Rest fallback ensuring safety
    if (householdId) {
      try {
        await updateShoppingItem(householdId, listId, itemId, { checked: nextChecked });
        mutateList();
      } catch (err) {
        console.error('Persistent toggle sync fail', err);
        mutateList();
      }
    }
  };

  // 2. Handle Item Mutations
  const handleAddItem = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!householdId) return;
    setIsAdding(true);
    try {
      const updated = await addShoppingItem(householdId, listId, {
        productId: selectedProductId || undefined,
        customName: !selectedProductId ? customItemName.trim() : undefined,
        quantity: qty,
        unit: unit as any,
        notes: notes.trim() || undefined,
      });
      
      mutateList(updated);
      // Clear inputs
      setSelectedProductId('');
      setCustomItemName('');
      setQty(1);
      setNotes('');
    } catch (err: any) {
      alert(err.message);
    } finally {
      setIsAdding(false);
    }
  };

  const handleDeleteItem = async (itemId: string) => {
    if (!householdId) return;

    // Optimistic delete
    mutateList(async (prev: any) => ({
      ...prev,
      items: prev.items.filter((it: any) => it.id !== itemId)
    }), { revalidate: false });

    try {
      const updated = await removeShoppingItem(householdId, listId, itemId);
      mutateList(updated);
    } catch (err: any) {
      window.alert(err.message);
      mutateList();
    }
  };

  // 3. Execute Final Checkout / Pantry Sync
  const handleSyncToPantry = async () => {
    if (!householdId || !list) return;
    const readyItems = list.items.filter((i: any) => i.checked && !i.addedToPantry);
    if (readyItems.length === 0) return;

    if (!window.confirm(`Import ${readyItems.length} checked ingredients directly into active Pantry stock?`)) return;

    try {
      const res = await syncToPantry(householdId, listId);
      window.alert(`Success! Provisioned ${res.addedCount} items into Pantry stock.`);
      
      // Mark list as completed automatically if all are done
      const allChecked = list.items.every((i: any) => i.checked || i.addedToPantry);
      if (allChecked) {
        await updateShoppingList(householdId, listId, { status: 'completed' as any });
      }

      mutateList();
    } catch (err: any) {
      window.alert('Migration sync error: ' + err.message);
    }
  };

  // Collate items categorized for satisfying view
  const categorizedItems = useMemo(() => {
    if (!list) return {};
    const groups: Record<string, any[]> = {};
    list.items.forEach((it: any) => {
      const cat = it.category || 'Other / Misc';
      if (!groups[cat]) groups[cat] = [];
      groups[cat].push(it);
    });
    return groups;
  }, [list]);

  if (isAuthLoading || listLoading) return <div style={{ padding: 40 }}>Hydrating session checklist...</div>;
  if (error || !list) return <div style={{ padding: 40, color: 'var(--danger)' }}>Error: {error}</div>;

  const itemsPendingSync = list.items.filter((i: any) => i.checked && !i.addedToPantry).length;
  const checkedCount = list.items.filter((i: any) => i.checked).length;
  const totalCount = list.items.length;

  return (
    <>
      <SetPageHeader
        title={list.name}
        subtitle="Perform live checkout check-offs synchronously across multiple household devices."
      />

      <div style={{ display: 'flex', alignItems: 'center', gap: 16, fontSize: 13, padding: '0 32px', marginTop: -12, marginBottom: 12, maxWidth: 1400, margin: '-12px auto 12px' }}>
        <Pill tone={list.status === 'completed' ? 'ok' : 'info'}>{list.status}</Pill>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, color: 'var(--ink-muted)' }}>
          <div style={{
            width: 8, height: 8, borderRadius: '50%',
            background: isConnected ? 'var(--success, #10b981)' : 'var(--danger, #ef4444)',
            boxShadow: isConnected ? '0 0 8px var(--success)' : 'none',
          }} />
          {isConnected ? 'Live Sync Channel Operational' : 'Connecting Sync...'}
        </div>
      </div>

      <div style={{ padding: '28px 32px 64px', maxWidth: 1400, margin: '0 auto' }}>
        
        {/* Top Action Strip */}
        <div style={{ display: 'flex', gap: 12, marginBottom: 24, justifyContent: 'space-between', flexWrap: 'wrap' }}>
          <Button variant="ghost" onClick={() => router.push('/shopping-lists')}>
            <Icon name="chevronLeft" style={{ marginRight: 6, width: 16 }} /> Back to Hub
          </Button>

          <div style={{ display: 'flex', gap: 12 }}>
            <Button variant="ghost" onClick={fetchComparisons}>
              <Icon name="trend" style={{ marginRight: 6, width: 16 }} /> Check Lowest Store Options
            </Button>
            {itemsPendingSync > 0 && (
              <Button onClick={handleSyncToPantry} style={{ background: 'var(--success)', borderColor: 'var(--success)', color: '#fff' }}>
                <Icon name="box" style={{ marginRight: 6, width: 16 }} /> Sync {itemsPendingSync} items to Pantry
              </Button>
            )}
          </div>
        </div>

        {/* Main Workspace Split Grid */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 380px', gap: 32, alignItems: 'start' }}>
          
          {/* Left: Categorized Checklist Grid */}
          <div>
            {totalCount === 0 ? (
              <Card style={{ padding: 40, textAlign: 'center', background: 'var(--bg-elev)', border: '1px dashed var(--border)' }}>
                <Icon name="list" style={{ width: 40, color: 'var(--ink-muted)', marginBottom: 16 }} />
                <h4 style={{ fontSize: 16, fontWeight: 600, color: 'var(--ink)' }}>Checklist is Empty</h4>
                <p style={{ fontSize: 13, color: 'var(--ink-muted)' }}>Add missing ingredients using the pane on the right.</p>
              </Card>
            ) : (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
                {Object.entries(categorizedItems).map(([cat, items]: [string, any]) => (
                  <div key={cat}>
                    <h4 style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink-muted)', textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 12, borderBottom: '1px solid var(--border)', paddingBottom: 6 }}>
                      {cat}
                    </h4>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                      {items.map((it: any) => (
                        <div
                          key={it.id}
                          style={{
                            display: 'flex', alignItems: 'center', gap: 14,
                            padding: '12px 16px', background: 'var(--bg-elev)',
                            border: '1px solid var(--border)', borderRadius: 'var(--r-md)',
                            transition: 'all 0.15s',
                            opacity: it.checked ? 0.65 : 1,
                            textDecoration: it.checked ? 'line-through' : 'none',
                          }}
                        >
                          {/* Checkbox circle */}
                          <button
                            onClick={() => handleToggleCheck(it.id, it.checked)}
                            aria-label={`Toggle check for ${it.productId ? products.find(p => p._id === it.productId)?.name : it.customName}`}
                            style={{
                              width: 22, height: 22, borderRadius: '50%',
                              border: `2px solid ${it.checked ? 'var(--success, #10b981)' : 'var(--border-hover)'}`,
                              background: it.checked ? 'var(--success, #10b981)' : 'transparent',
                              display: 'flex', alignItems: 'center', justifyContent: 'center',
                              cursor: 'pointer', flexShrink: 0, padding: 0,
                            }}
                          >
                            {it.checked && <Icon name="check" style={{ width: 12, color: '#fff' }} />}
                          </button>

                          <div style={{ flex: 1, minWidth: 0 }}>
                            <div style={{ fontWeight: 600, fontSize: 14, color: it.checked ? 'var(--ink-muted)' : 'var(--ink)' }}>
                              {it.productId ? products.find(p => p._id === it.productId)?.name || 'Ingredient Loading...' : it.customName}
                            </div>
                            <div style={{ fontSize: 11, color: 'var(--ink-muted)', display: 'flex', gap: 10, marginTop: 2 }}>
                              <span>Qty: {it.quantity} {it.unit}</span>
                              {it.notes && <span>• Note: {it.notes}</span>}
                            </div>
                          </div>

                          {/* Estimated Price Tag */}
                          {it.estimatedPrice && !it.checked && (
                            <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink-muted)', background: 'var(--bg)', padding: '4px 8px', borderRadius: 'var(--r-sm)' }}>
                              ~${it.estimatedPrice.toFixed(2)}
                            </div>
                          )}

                          {/* Migrated Badge */}
                          {it.addedToPantry && (
                            <Pill tone="ok">
                              <Icon name="box" style={{ width: 10, marginRight: 4 }} /> Pantry
                            </Pill>
                          )}

                          <button
                            onClick={() => handleDeleteItem(it.id)}
                            aria-label={`Delete ${it.productId ? products.find(p => p._id === it.productId)?.name : it.customName}`}
                            style={{ border: 'none', background: 'transparent', cursor: 'pointer', padding: 6, color: 'var(--ink-muted)', opacity: 0.5 }}
                          >
                            <Icon name="trash" style={{ width: 14 }} />
                          </button>
                        </div>
                      ))}
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* Right Side Panel: Context Inputs */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
            
            {/* Pane A: Add New Item */}
            <Card style={{ padding: 20 }}>
              <h4 style={{ fontSize: 15, fontWeight: 600, marginBottom: 16, display: 'flex', alignItems: 'center', gap: 8 }}>
                <Icon name="plus" style={{ width: 16 }} /> Add Grocery Item
              </h4>
              <form onSubmit={handleAddItem} style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
                <div>
                  <label style={labelStyle}>Link Product Catalog</label>
                  <select
                    value={selectedProductId}
                    onChange={(e) => {
                      setSelectedProductId(e.target.value);
                      if (e.target.value) setCustomItemName('');
                    }}
                    style={selectStyle}
                  >
                    <option value="">-- Create Manual Custom Input --</option>
                    {products.map(p => <option key={p._id} value={p._id}>{p.name}</option>)}
                  </select>
                </div>

                {!selectedProductId && (
                  <div>
                    <label style={labelStyle}>Custom Custom Name</label>
                    <input
                      type="text"
                      required
                      placeholder="e.g., Generic Flour"
                      value={customItemName}
                      onChange={e => setCustomItemName(e.target.value)}
                      style={inputStyle}
                    />
                  </div>
                )}

                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                  <div>
                    <label style={labelStyle}>Quantity</label>
                    <input
                      type="number"
                      required
                      min="0.01"
                      step="any"
                      value={qty}
                      onChange={e => setQty(parseFloat(e.target.value) || 0)}
                      style={inputStyle}
                    />
                  </div>
                  <div>
                    <label style={labelStyle}>Unit</label>
                    <select value={unit} onChange={e => setUnit(e.target.value)} style={selectStyle}>
                      <option value="g">Grams</option>
                      <option value="ml">Milliliters</option>
                      <option value="piece">Pieces</option>
                      <option value="slice">Slices</option>
                    </select>
                  </div>
                </div>

                <div>
                  <label style={labelStyle}>Notes</label>
                  <input
                    type="text"
                    placeholder="Brand preference, etc."
                    value={notes}
                    onChange={e => setNotes(e.target.value)}
                    style={inputStyle}
                  />
                </div>

                <Button type="submit" disabled={isAdding} style={{ width: '100%' }}>
                  {isAdding ? 'Appending...' : 'Add to List'}
                </Button>
              </form>
            </Card>

            {/* Pane B: Real-Time Store Optimizer */}
            {storeOptions.length > 0 && (
              <Card style={{ padding: 20 }}>
                <h4 style={{ fontSize: 15, fontWeight: 600, marginBottom: 16, display: 'flex', alignItems: 'center', gap: 8 }}>
                  <Icon name="trend" style={{ width: 16, color: 'var(--brand)' }} /> Lowest Store Basket Rank
                </h4>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                  {storeOptions.map((opt, idx) => (
                    <div key={opt.storeId} style={{ padding: 12, background: 'var(--bg)', border: idx === 0 ? '1px solid var(--success)' : '1px solid var(--border)', borderRadius: 'var(--r-md)' }}>
                      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                        <span style={{ fontWeight: 600, color: 'var(--ink)', fontSize: 13 }}>{opt.storeName}</span>
                        <span style={{ fontSize: 14, fontWeight: 700, color: idx === 0 ? 'var(--success)' : 'var(--ink)' }}>${opt.estimatedTotal.toFixed(2)}</span>
                      </div>
                      <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, color: 'var(--ink-muted)', marginTop: 4 }}>
                        <span>Covered: {opt.itemsCovered}/{totalCount} products</span>
                        {idx === 0 && <span style={{ color: 'var(--success)', fontWeight: 600 }}>Cheapest Single Trip</span>}
                      </div>
                    </div>
                  ))}
                </div>
              </Card>
            )}
          </div>
        </div>
      </div>
    </>
  );
}

const labelStyle: React.CSSProperties = {
  display: 'block', fontSize: 11, fontWeight: 600, color: 'var(--ink-muted)',
  textTransform: 'uppercase', letterSpacing: '0.03em', marginBottom: 6,
};

const inputStyle: React.CSSProperties = {
  width: '100%', padding: '8px 12px', borderRadius: 'var(--r-md)',
  background: 'var(--bg)', border: '1px solid var(--border)', color: 'var(--ink)',
  fontSize: 13, outline: 'none',
};

const selectStyle: React.CSSProperties = {
  width: '100%', padding: '8px 12px', borderRadius: 'var(--r-md)',
  background: 'var(--bg)', border: '1px solid var(--border)', color: 'var(--ink)',
  fontSize: 13, outline: 'none', height: 36,
};
