'use client';

import { useState, useEffect, useCallback, useRef, useMemo } from 'react';
import useSWR, { mutate } from 'swr';
import { listPantryItems, transitionPantryItem, deletePantryItem } from '@/services/pantry';
import { StorageLocation, ItemStatus, FreshnessUrgency } from '@meshitrack/shared';
import type { z } from 'zod/v4';
import type { PantryItemResponseSchema } from '@meshitrack/shared';

type PantryItem = z.infer<typeof PantryItemResponseSchema>;

const STORAGE_TABS = [
  { value: '', label: 'All' },
  { value: StorageLocation.FRIDGE, label: 'Fridge' },
  { value: StorageLocation.FREEZER, label: 'Freezer' },
  { value: StorageLocation.PANTRY, label: 'Pantry' },
  { value: StorageLocation.COUNTER, label: 'Counter' },
] as const;

const URGENCY_COLORS: Record<string, { bg: string; color: string; label: string }> = {
  [FreshnessUrgency.FRESH]: {
    bg: 'var(--success-soft, #d4edda)',
    color: 'var(--success, #28a745)',
    label: 'Fresh',
  },
  [FreshnessUrgency.USE_SOON]: {
    bg: 'var(--warning-soft, #fff3cd)',
    color: 'var(--warning, #856404)',
    label: 'Use soon',
  },
  [FreshnessUrgency.URGENT]: { bg: 'var(--danger-soft)', color: 'var(--danger)', label: 'Urgent' },
  [FreshnessUrgency.CHECK]: { bg: 'var(--danger-soft)', color: 'var(--danger)', label: 'Check' },
  [FreshnessUrgency.EXPIRED]: {
    bg: 'var(--danger-soft)',
    color: 'var(--danger)',
    label: 'Expired',
  },
};

const STATUS_LABELS: Record<string, string> = {
  [ItemStatus.SEALED]: 'Sealed',
  [ItemStatus.OPENED]: 'Opened',
  [ItemStatus.PREPARED]: 'Prepared',
  [ItemStatus.CONSUMED]: 'Consumed',
  [ItemStatus.DISCARDED]: 'Discarded',
  [ItemStatus.EXPIRED]: 'Expired',
};

const VALID_TRANSITIONS: Record<string, string[]> = {
  [ItemStatus.SEALED]: [ItemStatus.OPENED, ItemStatus.CONSUMED, ItemStatus.DISCARDED],
  [ItemStatus.OPENED]: [ItemStatus.PREPARED, ItemStatus.CONSUMED, ItemStatus.DISCARDED],
  [ItemStatus.PREPARED]: [ItemStatus.CONSUMED, ItemStatus.DISCARDED],
};

const TRANSITION_LABELS: Record<string, string> = {
  [ItemStatus.OPENED]: 'Open',
  [ItemStatus.PREPARED]: 'Prepare',
  [ItemStatus.CONSUMED]: 'Consume',
  [ItemStatus.DISCARDED]: 'Discard',
};

export function PantryList({ householdId }: { householdId: string }) {
  const [error, setError] = useState('');
  const [storageFilter, setStorageFilter] = useState('');
  const [statusFilter, setStatusFilter] = useState('');

  const query = useMemo(() => ({
    storageLocation: storageFilter || undefined,
    status: statusFilter || undefined,
    limit: 50,
  }), [storageFilter, statusFilter]);

  const swrKey = householdId ? `pantry-${householdId}-${JSON.stringify(query)}` : null;
  const { data: pantryResponse, mutate: mutatePantry, isLoading: loading, error: swrError } = useSWR(
    swrKey,
    () => listPantryItems(householdId, query)
  );

  const items = pantryResponse?.data ?? [];

  useEffect(() => {
    if (swrError) setError(swrError instanceof Error ? swrError.message : 'Failed to load pantry');
  }, [swrError]);

  async function handleTransition(id: string, status: string) {
    // Optimistic update
    mutatePantry(async (current: any) => {
      if (!current) return current;
      return {
        ...current,
        data: current.data.map((item: any) => (item._id === id ? { ...item, status } : item))
      };
    }, { revalidate: false });

    try {
      const updated = await transitionPantryItem(householdId, id, { status } as never);
      mutatePantry();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Transition failed');
      mutatePantry();
    }
  }

  async function handleDelete(id: string, name: string) {
    if (!window.confirm(`Delete "${name}"?`)) return;

    // Optimistic delete
    mutatePantry(async (current: any) => {
      if (!current) return current;
      return {
        ...current,
        data: current.data.filter((item: any) => item._id !== id)
      };
    }, { revalidate: false });

    try {
      await deletePantryItem(householdId, id);
      mutatePantry();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to delete');
      mutatePantry();
    }
  }

  return (
    <div style={{ padding: '28px 32px 56px', maxWidth: 1200 }}>
      {/* Storage tabs */}
      <div
        style={{
          display: 'flex',
          gap: 4,
          marginBottom: 16,
          borderBottom: '1px solid var(--border)',
          paddingBottom: 0,
        }}
      >
        {STORAGE_TABS.map((tab) => {
          const isActive = storageFilter === tab.value;
          return (
            <button
              key={tab.value}
              onClick={() => setStorageFilter(tab.value)}
              style={{
                padding: '8px 16px',
                fontSize: 13,
                fontWeight: isActive ? 600 : 400,
                color: isActive ? 'var(--brand)' : 'var(--ink-muted)',
                background: 'transparent',
                border: 'none',
                borderBottom: isActive ? '2px solid var(--brand)' : '2px solid transparent',
                cursor: 'pointer',
                marginBottom: -1,
              }}
            >
              {tab.label}
            </button>
          );
        })}
      </div>

      {/* Status filter */}
      <div style={{ display: 'flex', gap: 12, marginBottom: 24, alignItems: 'center' }}>
        <select
          value={statusFilter}
          onChange={(e) => setStatusFilter(e.target.value)}
          style={{
            padding: '8px 12px',
            borderRadius: 'var(--r-md)',
            border: '1px solid var(--border)',
            background: 'var(--bg-elev)',
            color: 'var(--ink)',
            fontSize: 14,
          }}
        >
          <option value="">All statuses</option>
          <option value="sealed">Sealed</option>
          <option value="opened">Opened</option>
          <option value="prepared">Prepared</option>
        </select>
      </div>

      {error && <p style={{ color: 'var(--danger)', marginBottom: 16, fontSize: 14 }}>{error}</p>}

      {loading ? (
        <div
          style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))',
            gap: 16,
          }}
        >
          {[...Array(6)].map((_, i) => (
            <div
              key={i}
              style={{
                height: 140,
                background: 'var(--bg-elev)',
                borderRadius: 'var(--r-md)',
                opacity: 0.5,
              }}
            />
          ))}
        </div>
      ) : items.length === 0 ? (
        <div
          style={{
            textAlign: 'center',
            padding: '64px 24px',
            color: 'var(--ink-muted)',
            fontSize: 14,
          }}
        >
          {storageFilter || statusFilter
            ? 'No items match your filters.'
            : 'No pantry items yet. Add your first item.'}
        </div>
      ) : (
        <div
          style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))',
            gap: 16,
          }}
        >
          {items.map((item) => (
            <PantryCard
              key={item._id}
              item={item}
              onTransition={handleTransition}
              onDelete={handleDelete}
            />
          ))}
        </div>
      )}
    </div>
  );
}

function PantryCard({
  item,
  onTransition,
  onDelete,
}: {
  item: PantryItem;
  onTransition: (id: string, status: string) => void;
  onDelete: (id: string, name: string) => void;
}) {
  const urgency =
    URGENCY_COLORS[item.freshnessEstimate.urgency] ?? URGENCY_COLORS[FreshnessUrgency.FRESH];
  const transitions = VALID_TRANSITIONS[item.status] ?? [];
  const daysText =
    item.freshnessEstimate.daysRemaining >= 0
      ? `${item.freshnessEstimate.daysRemaining}d left`
      : `${Math.abs(item.freshnessEstimate.daysRemaining)}d overdue`;

  return (
    <div
      style={{
        background: 'var(--bg-elev)',
        border: '1px solid var(--border)',
        borderRadius: 'var(--r-md)',
        padding: 16,
        display: 'flex',
        flexDirection: 'column',
        gap: 10,
      }}
    >
      {/* Header row */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div
            style={{
              fontWeight: 600,
              fontSize: 14,
              color: 'var(--ink)',
              overflow: 'hidden',
              textOverflow: 'ellipsis',
              whiteSpace: 'nowrap',
            }}
          >
            {item.productName}
          </div>
          <div style={{ fontSize: 12, color: 'var(--ink-muted)', marginTop: 2 }}>
            {item.quantity} {item.unit}
          </div>
        </div>
        <span
          style={{
            display: 'inline-block',
            padding: '2px 8px',
            borderRadius: 'var(--r-sm)',
            fontSize: 11,
            fontWeight: 600,
            background: urgency.bg,
            color: urgency.color,
            whiteSpace: 'nowrap',
          }}
        >
          {urgency.label}
        </span>
      </div>

      {/* Info */}
      <div style={{ fontSize: 12, color: 'var(--ink-muted)', display: 'flex', gap: 12 }}>
        <span>{STATUS_LABELS[item.status] ?? item.status}</span>
        <span>{daysText}</span>
        <span style={{ textTransform: 'capitalize' }}>{item.storageLocation}</span>
      </div>

      {/* Actions */}
      {transitions.length > 0 && (
        <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 'auto' }}>
          {transitions.map((status) => (
            <button
              key={status}
              onClick={() => onTransition(item._id, status)}
              style={{
                padding: '4px 10px',
                fontSize: 12,
                borderRadius: 'var(--r-sm)',
                border: '1px solid var(--border)',
                background: status === ItemStatus.CONSUMED ? 'var(--brand-soft)' : 'var(--bg)',
                color: status === ItemStatus.CONSUMED ? 'var(--brand)' : 'var(--ink-muted)',
                cursor: 'pointer',
                fontWeight: status === ItemStatus.CONSUMED ? 600 : 400,
              }}
            >
              {TRANSITION_LABELS[status] ?? status}
            </button>
          ))}
          <button
            onClick={() => onDelete(item._id, item.productName)}
            style={{
              padding: '4px 10px',
              fontSize: 12,
              borderRadius: 'var(--r-sm)',
              border: '1px solid var(--border)',
              background: 'var(--bg)',
              color: 'var(--danger)',
              cursor: 'pointer',
              marginLeft: 'auto',
            }}
          >
            Delete
          </button>
        </div>
      )}
    </div>
  );
}
