'use client';

import { useState, useEffect, useCallback } from 'react';
import { useApi } from '@/lib/useApi';
import { SetPageHeader } from '@/components/layout/SetPageHeader';
import { Card, Button, Icon, Pill } from '@/components/ui';
import { getShoppingLists, createShoppingList } from '@/services/shopping-lists';
import { listMealPlans } from '@/services/meal-plans';
import { generateFromMealPlan } from '@/services/shopping-lists';
import Link from 'next/link';

export default function ShoppingListsPage() {
  const { householdId, isLoading } = useApi();
  const [lists, setLists] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  
  // Modal States
  const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
  const [isGapModalOpen, setIsGapModalOpen] = useState(false);
  
  // Form States
  const [newListName, setNewListName] = useState('');
  const [recentMealPlans, setRecentMealPlans] = useState<any[]>([]);
  const [mealPlanLoading, setMealPlanLoading] = useState(false);

  const fetchLists = useCallback(async () => {
    if (!householdId) return;
    setLoading(true);
    try {
      const data = await getShoppingLists(householdId);
      // Sort by active status first, then newest first
      data.sort((a, b) => {
        if (a.status === 'active' && b.status !== 'active') return -1;
        if (a.status !== 'active' && b.status === 'active') return 1;
        return new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
      });
      setLists(data);
    } catch (err: any) {
      setError(err.message || 'Failed to load shopping lists');
    } finally {
      setLoading(false);
    }
  }, [householdId]);

  useEffect(() => {
    fetchLists();
  }, [fetchLists]);

  const handleCreateList = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newListName.trim() || !householdId) return;
    try {
      const res = await createShoppingList(householdId, {
        name: newListName.trim(),
        items: [],
      });
      setNewListName('');
      setIsCreateModalOpen(false);
      // Redirect or update list
      setLists((prev) => [res, ...prev]);
    } catch (err: any) {
      alert(err.message || 'Failed to create list');
    }
  };

  const openGapModal = async () => {
    setIsGapModalOpen(true);
    if (!householdId) return;
    setMealPlanLoading(true);
    try {
      const plans = await listMealPlans(householdId);
      setRecentMealPlans(plans.data || []);
    } catch (err) {
      console.error(err);
    } finally {
      setMealPlanLoading(false);
    }
  };

  const handleGenerateFromPlan = async (mealPlanId: string) => {
    if (!householdId) return;
    try {
      const res = await generateFromMealPlan(householdId, mealPlanId);
      setIsGapModalOpen(false);
      setLists((prev) => [res, ...prev]);
    } catch (err: any) {
      alert(err.message || 'Failed to generate groceries from meal plan');
    }
  };

  if (isLoading) return <SetPageHeader title="Groceries" subtitle="Analyze needs and track baskets" />;
  if (!householdId) return <div style={{ padding: 32 }}>Please join a household.</div>;

  const activeLists = lists.filter(l => l.status === 'active' || l.status === 'shopping');
  const completedLists = lists.filter(l => l.status === 'completed' || l.status === 'archived');
  
  // Derive stats
  const totalActiveCost = activeLists.reduce((sum, l) => sum + (l.totalEstimatedCost || 0), 0);
  const totalPendingItems = activeLists.reduce((sum, l) => sum + l.items.filter((i: any) => !i.checked).length, 0);

  return (
    <>
      <SetPageHeader title="Grocery & Shopping" subtitle="Streamline your checklist, check gaps, and compare costs." />
      
      <div style={{ padding: '28px 32px 64px', maxWidth: 1300, margin: '0 auto' }}>
        {/* 1. Beautiful Stats Band */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(240px, 1fr))', gap: 20, marginBottom: 32 }}>
          <MetricCard
            icon="store"
            title="Active Lists"
            value={String(activeLists.length)}
            subtitle="Ready to shop"
            color="var(--brand)"
          />
          <MetricCard
            icon="list"
            title="Pending Items"
            value={String(totalPendingItems)}
            subtitle="Across all active trips"
            color="var(--warning, #f59e0b)"
          />
          <MetricCard
            icon="tag"
            title="Est. Total Value"
            value={`$${totalActiveCost.toFixed(2)}`}
            subtitle="Estimated current cart"
            color="var(--success, #10b981)"
          />
          <MetricCard
            icon="trend"
            title="Spending Trend"
            value="Analyics"
            subtitle="Visualize price fluctuations"
            color="var(--ink-muted)"
            link="/shopping-lists/prices"
          />
        </div>

        {/* 2. Action Row */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24, flexWrap: 'wrap', gap: 16 }}>
          <h3 style={{ fontSize: 18, fontWeight: 600, color: 'var(--ink)' }}>Checklists & Baskets</h3>
          <div style={{ display: 'flex', gap: 12 }}>
            <Button variant="ghost" onClick={openGapModal}>
              <Icon name="zap" style={{ marginRight: 6, width: 16 }} />
              Generate from Meal Plan
            </Button>
            <Button onClick={() => setIsCreateModalOpen(true)}>
              <Icon name="plus" style={{ marginRight: 6, width: 16 }} />
              New Shopping List
            </Button>
          </div>
        </div>

        {error && <div style={{ color: 'var(--danger)', padding: 16, background: 'var(--danger-soft)', borderRadius: 'var(--r-md)', marginBottom: 24 }}>{error}</div>}

        {/* 3. Lists Grid */}
        {loading ? (
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(340px, 1fr))', gap: 20 }}>
            {[1, 2, 3].map(i => <div key={i} style={{ height: 180, borderRadius: 'var(--r-lg)', border: '1px solid var(--border)', background: 'var(--bg-elev)', opacity: 0.4 }} />)}
          </div>
        ) : activeLists.length === 0 && completedLists.length === 0 ? (
          <div style={{ textAlign: 'center', padding: '80px 24px', background: 'var(--bg-elev)', border: '1px dashed var(--border)', borderRadius: 'var(--r-lg)' }}>
            <Icon name="store" style={{ width: 48, height: 48, color: 'var(--ink-muted)', marginBottom: 16 }} />
            <h4 style={{ fontSize: 16, fontWeight: 600, color: 'var(--ink)', marginBottom: 8 }}>No Shopping Lists Found</h4>
            <p style={{ color: 'var(--ink-muted)', fontSize: 14, marginBottom: 24, maxWidth: 400, margin: '0 auto 24px' }}>
              Create an empty manual checklist, or dynamically auto-generate missing ingredients directly from your meal plan!
            </p>
            <Button onClick={() => setIsCreateModalOpen(true)}>Create First List</Button>
          </div>
        ) : (
          <>
            {/* Active Section */}
            {activeLists.length > 0 && (
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(340px, 1fr))', gap: 20, marginBottom: 40 }}>
                {activeLists.map((list) => (
                  <ShoppingListCard key={list._id} list={list} />
                ))}
              </div>
            )}

            {/* Past Section */}
            {completedLists.length > 0 && (
              <>
                <h4 style={{ fontSize: 14, fontWeight: 600, color: 'var(--ink-muted)', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 16 }}>Completed Runs</h4>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(340px, 1fr))', gap: 20 }}>
                  {completedLists.map((list) => (
                    <ShoppingListCard key={list._id} list={list} />
                  ))}
                </div>
              </>
            )}
          </>
        )}
      </div>

      {/* Creation Modal Dialog Overlay */}
      {isCreateModalOpen && (
        <div style={overlayStyle} onClick={() => setIsCreateModalOpen(false)}>
          <div style={modalStyle} onClick={(e) => e.stopPropagation()}>
            <h3 style={{ fontSize: 18, fontWeight: 600, marginBottom: 16 }}>Create Shopping List</h3>
            <form onSubmit={handleCreateList}>
              <div style={{ marginBottom: 20 }}>
                <label style={{ display: 'block', fontSize: 12, fontWeight: 500, color: 'var(--ink-muted)', marginBottom: 6 }}>Checklist Name</label>
                <input
                  type="text"
                  required
                  placeholder="e.g., Weekly Costco Run"
                  value={newListName}
                  onChange={(e) => setNewListName(e.target.value)}
                  style={inputStyle}
                  autoFocus
                />
              </div>
              <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 12 }}>
                <Button type="button" variant="ghost" onClick={() => setIsCreateModalOpen(false)}>Cancel</Button>
                <Button type="submit">Create</Button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Meal Plan Gap Generator Modal */}
      {isGapModalOpen && (
        <div style={overlayStyle} onClick={() => setIsGapModalOpen(false)}>
          <div style={modalStyle} onClick={(e) => e.stopPropagation()}>
            <h3 style={{ fontSize: 18, fontWeight: 600, marginBottom: 8 }}>Scan Meal Plan Gaps</h3>
            <p style={{ fontSize: 13, color: 'var(--ink-muted)', marginBottom: 20 }}>
              Select a scheduled weekly plan. We will cross-reference your recipe ingredient requirements vs active pantry inventory to auto-generate your grocery shortages!
            </p>
            
            {mealPlanLoading ? (
              <div style={{ textAlign: 'center', padding: 20 }}>Loading schedules...</div>
            ) : recentMealPlans.length === 0 ? (
              <div style={{ padding: 16, background: 'var(--bg)', border: '1px solid var(--border)', borderRadius: 8, textAlign: 'center', fontSize: 14, color: 'var(--ink-muted)' }}>
                No meal plans configured. Build a plan first!
              </div>
            ) : (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10, maxHeight: 300, overflowY: 'auto', marginBottom: 20 }}>
                {recentMealPlans.slice(0, 5).map((plan) => {
                  const dateStr = new Date(plan.weekStartDate).toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' });
                  return (
                    <button
                      key={plan._id}
                      onClick={() => handleGenerateFromPlan(plan._id)}
                      style={planRowStyle}
                    >
                      <div style={{ textAlign: 'left' }}>
                        <div style={{ fontWeight: 600, color: 'var(--ink)', fontSize: 14 }}>Week of {dateStr}</div>
                        <div style={{ fontSize: 12, color: 'var(--ink-muted)' }}>Status: <span style={{ textTransform: 'capitalize' }}>{plan.status}</span></div>
                      </div>
                      <Icon name="chevronRight" style={{ width: 16, color: 'var(--ink-muted)' }} />
                    </button>
                  );
                })}
              </div>
            )}
            
            <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
              <Button variant="ghost" onClick={() => setIsGapModalOpen(false)}>Close</Button>
            </div>
          </div>
        </div>
      )}
    </>
  );
}

function MetricCard({ icon, title, value, subtitle, color, link }: any) {
  const content = (
    <Card style={{ padding: 20, height: '100%', display: 'flex', alignItems: 'center', gap: 16, position: 'relative', overflow: 'hidden', cursor: link ? 'pointer' : 'default' }}>
      <div style={{ width: 48, height: 48, borderRadius: '50%', background: `${color}15`, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
        <Icon name={icon} style={{ width: 22, height: 22, color }} />
      </div>
      <div>
        <div style={{ fontSize: 12, fontWeight: 500, color: 'var(--ink-muted)', textTransform: 'uppercase', letterSpacing: '0.02em' }}>{title}</div>
        <div style={{ fontSize: 24, fontWeight: 700, color: 'var(--ink)', margin: '2px 0' }}>{value}</div>
        <div style={{ fontSize: 12, color: 'var(--ink-muted)', display: 'flex', alignItems: 'center', gap: 4 }}>
          {subtitle}
          {link && <Icon name="chevronRight" style={{ width: 12 }} />}
        </div>
      </div>
    </Card>
  );
  return link ? <Link href={link} style={{ textDecoration: 'none' }}>{content}</Link> : content;
}

function ShoppingListCard({ list }: { list: any }) {
  const total = list.items.length;
  const checked = list.items.filter((i: any) => i.checked).length;
  const progress = total > 0 ? Math.round((checked / total) * 100) : 0;
  const date = new Date(list.createdAt).toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
  
  const isActive = list.status === 'active' || list.status === 'shopping';
  
  return (
    <Link href={`/shopping-lists/${list._id}`} style={{ textDecoration: 'none' }}>
      <Card style={{
        padding: 20,
        transition: 'all 0.2s ease',
        border: isActive ? '1px solid var(--border-hover, #444)' : '1px solid var(--border)',
        position: 'relative',
        background: isActive ? 'rgba(255,255,255,0.02)' : 'var(--bg-elev)',
        display: 'flex',
        flexDirection: 'column',
        gap: 12,
        cursor: 'pointer',
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12 }}>
          <div>
            <h4 style={{ fontSize: 16, fontWeight: 600, color: 'var(--ink)', margin: 0, lineHeight: 1.3 }}>{list.name}</h4>
            <span style={{ fontSize: 11, color: 'var(--ink-muted)', display: 'inline-block', marginTop: 4 }}>Created {date}</span>
          </div>
          <Pill tone={list.status === 'active' ? 'info' : list.status === 'shopping' ? 'warn' : 'ghost'}>
            {list.status === 'shopping' ? 'Live' : list.status}
          </Pill>
        </div>

        <div style={{ fontSize: 13, color: 'var(--ink-muted)', display: 'flex', gap: 16, alignItems: 'center' }}>
          <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <Icon name="list" style={{ width: 14 }} /> {checked}/{total} items
          </span>
          {list.totalEstimatedCost && (
            <span style={{ display: 'flex', alignItems: 'center', gap: 4, fontWeight: 600, color: 'var(--ink)' }}>
              ${list.totalEstimatedCost.toFixed(2)}
            </span>
          )}
        </div>

        {/* Custom Progress Bar */}
        <div>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, color: 'var(--ink-muted)', marginBottom: 4 }}>
            <span>Progress</span>
            <span>{progress}%</span>
          </div>
          <div style={{ height: 6, background: 'var(--border)', borderRadius: 3, overflow: 'hidden' }}>
            <div style={{ height: '100%', width: `${progress}%`, background: progress === 100 ? 'var(--success, #10b981)' : 'var(--brand)', borderRadius: 3, transition: 'width 0.4s cubic-bezier(0.4, 0, 0.2, 1)' }} />
          </div>
        </div>
      </Card>
    </Link>
  );
}

const overlayStyle: React.CSSProperties = {
  position: 'fixed', top: 0, left: 0, right: 0, bottom: 0,
  background: 'rgba(0,0,0,0.6)', backdropFilter: 'blur(6px)',
  display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 9999,
  padding: 16,
};

const modalStyle: React.CSSProperties = {
  background: 'var(--bg-elev)', border: '1px solid var(--border)',
  borderRadius: 'var(--r-lg)', padding: 24, width: '100%', maxWidth: 460,
  boxShadow: '0 20px 40px rgba(0,0,0,0.3)',
};

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

const planRowStyle: React.CSSProperties = {
  display: 'flex', justifyContent: 'space-between', alignItems: 'center',
  padding: '12px 16px', background: 'var(--bg)', border: '1px solid var(--border)',
  borderRadius: 'var(--r-md)', width: '100%', cursor: 'pointer', transition: 'all 0.15s',
};
