import { useState, useEffect, useCallback } from 'react';
import api from '../utils/api';
import { timeAgo } from '../utils/helpers';
import { useAuth } from '../context/AuthContext';
import { Icons } from '../components/icons/Icons';
import Confirm from '../components/ui/Confirm';

const TYPE_ICONS = {
  product: Icons.Box,
  order: Icons.Cart,
  client: Icons.Users,
  stock_report: Icons.Clipboard,
  user: Icons.User,
  system: Icons.Alert,
  follow_up: Icons.Cal,
};

const TYPE_COLORS = {
  product: 'text-gr',
  order: 'text-ac',
  client: 'text-pr',
  stock_report: 'text-yl',
  user: 'text-or',
  system: 'text-rd',
  follow_up: 'text-ac',
};

const ACTION_COLORS = {
  created: 'bg-gr/15 text-gr',
  placed: 'bg-gr/15 text-gr',
  edited: 'bg-ac/15 text-ac',
  deleted: 'bg-rd/15 text-rd',
  cancelled: 'bg-yl/15 text-yl',
  refunded: 'bg-rd/15 text-rd',
  low_stock: 'bg-rd/15 text-rd',
  stock_increased: 'bg-gr/15 text-gr',
  stock_decreased: 'bg-or/15 text-or',
  vip_toggled: 'bg-gold/15 text-gold',
  submitted: 'bg-yl/15 text-yl',
  processed: 'bg-ac/15 text-ac',
  resolved: 'bg-gr/15 text-gr',
  completed: 'bg-gr/15 text-gr',
  log_full: 'bg-or/15 text-or',
  delivery_updated: 'bg-ac/15 text-ac',
};

const CATEGORIES = [
  { key: 'all', label: 'All' },
  { key: 'inventory', label: 'Inventory' },
  { key: 'orders', label: 'Orders' },
  { key: 'clients', label: 'Clients' },
  { key: 'system', label: 'System' },
  { key: 'stock_reports', label: 'Stock Reports' },
  { key: 'users', label: 'Users' },
];

export default function NotificationCenter({ onUnreadChange }) {
  const { hasRole } = useAuth();
  const [notifications, setNotifications] = useState([]);
  const [category, setCategory] = useState('all');
  const [categoryCounts, setCategoryCounts] = useState({});
  const [loading, setLoading] = useState(false);
  const [expanded, setExpanded] = useState(null);
  const [deleteAllCfm, setDeleteAllCfm] = useState(false);
  const [offset, setOffset] = useState(0);
  const [hasMore, setHasMore] = useState(true);
  const LIMIT = 30;

  const fetchNotifications = useCallback(async (reset = false) => {
    try {
      setLoading(true);
      const newOffset = reset ? 0 : offset;
      const res = await api.get(`/notifications?category=${category}&limit=${LIMIT}&offset=${newOffset}`);
      if (reset) {
        setNotifications(res.data);
        setOffset(res.data.length);
      } else {
        setNotifications(prev => [...prev, ...res.data]);
        setOffset(newOffset + res.data.length);
      }
      setHasMore(res.data.length === LIMIT);
    } catch {} finally {
      setLoading(false);
    }
  }, [category, offset]);

  const fetchCounts = async () => {
    try {
      const res = await api.get('/notifications/category-counts');
      setCategoryCounts(res.data);
    } catch {}
  };

  const refreshUnread = async () => {
    try {
      const res = await api.get('/notifications/unread-count');
      onUnreadChange?.(res.data.count || 0);
    } catch {}
  };

  useEffect(() => {
    setOffset(0);
    setHasMore(true);
    setNotifications([]);
    // fetch with reset
    (async () => {
      try {
        setLoading(true);
        const res = await api.get(`/notifications?category=${category}&limit=${LIMIT}&offset=0`);
        setNotifications(res.data);
        setOffset(res.data.length);
        setHasMore(res.data.length === LIMIT);
      } catch {} finally { setLoading(false); }
    })();
    fetchCounts();
  }, [category]);

  const markRead = async (id) => {
    await api.put(`/notifications/${id}/read`);
    setNotifications(prev => prev.map(n => n.id === id ? { ...n, is_read: 1 } : n));
    refreshUnread();
    fetchCounts();
  };

  const markAllRead = async () => {
    await api.put('/notifications/read-all');
    setNotifications(prev => prev.map(n => ({ ...n, is_read: 1 })));
    refreshUnread();
    fetchCounts();
  };

  const deleteOne = async (id) => {
    await api.delete(`/notifications/${id}`);
    setNotifications(prev => prev.filter(n => n.id !== id));
    refreshUnread();
    fetchCounts();
  };

  const deleteAll = async () => {
    await api.delete('/notifications');
    setNotifications([]);
    setDeleteAllCfm(false);
    refreshUnread();
    fetchCounts();
  };

  const totalUnread = Object.values(categoryCounts).reduce((s, v) => s + v, 0);

  return (
    <div>
      <div className="flex justify-between items-center mb-1">
        <div>
          <h1 className="text-xl font-bold mb-0.5">Notification Center</h1>
          <p className="text-t2 text-xs mb-5">
            {totalUnread > 0 ? `${totalUnread} unread` : 'All caught up'}
          </p>
        </div>
        <div className="flex gap-1.5">
          {totalUnread > 0 && (
            <button className="px-3 py-1.5 rounded-md border border-bd text-t2 text-xs font-semibold hover:bg-s2 flex items-center gap-1" onClick={markAllRead}>
              <Icons.Check /> Mark All Read
            </button>
          )}
          {notifications.length > 0 && (
            <button className="px-3 py-1.5 rounded-md border border-rd/30 text-rd text-xs font-semibold hover:bg-rd/10 flex items-center gap-1" onClick={() => setDeleteAllCfm(true)}>
              <Icons.Trash /> Delete All
            </button>
          )}
        </div>
      </div>

      {/* Category Tabs */}
      <div className="flex gap-1.5 mb-4 flex-wrap">
        {CATEGORIES.map((c) => {
          const countForCat = c.key === 'all' ? totalUnread :
            c.key === 'inventory' ? (categoryCounts.product || 0) :
            c.key === 'orders' ? (categoryCounts.order || 0) :
            c.key === 'clients' ? (categoryCounts.client || 0) :
            c.key === 'system' ? (categoryCounts.system || 0) :
            c.key === 'stock_reports' ? (categoryCounts.stock_report || 0) :
            c.key === 'users' ? (categoryCounts.user || 0) : 0;
          return (
            <button
              key={c.key}
              className={`px-3 py-1.5 rounded-md text-[11px] font-semibold border flex items-center gap-1.5 ${
                category === c.key ? 'bg-ac text-white border-ac' : 'border-bd text-t2 hover:bg-s2'
              }`}
              onClick={() => setCategory(c.key)}
            >
              {c.label}
              {countForCat > 0 && (
                <span className={`rounded-full min-w-[16px] h-4 flex items-center justify-center text-[9px] font-bold px-1 ${
                  category === c.key ? 'bg-white/20 text-white' : 'bg-rd text-white'
                }`}>{countForCat}</span>
              )}
            </button>
          );
        })}
      </div>

      {/* Notification List */}
      <div className="bg-s1 border border-bd rounded-[10px] overflow-hidden">
        {notifications.length === 0 && !loading ? (
          <div className="text-center py-12">
            <div className="text-t3 mb-2"><Icons.Bell /></div>
            <p className="text-t2 text-xs">No notifications</p>
          </div>
        ) : (
          notifications.map((n) => {
            const Icon = TYPE_ICONS[n.type] || Icons.Bell;
            const isExpanded = expanded === n.id;
            return (
              <div key={n.id} className={`border-b border-bd last:border-0 transition-colors ${!n.is_read ? 'bg-ac/[0.03] border-l-[3px] border-l-ac' : ''}`}>
                {/* Main row */}
                <div className="flex items-start gap-3 p-3.5 cursor-pointer group" onClick={() => { setExpanded(isExpanded ? null : n.id); if (!n.is_read) markRead(n.id); }}>
                  <div className={`flex-shrink-0 mt-0.5 ${TYPE_COLORS[n.type] || 'text-t2'}`}>
                    <Icon />
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 mb-0.5">
                      <span className="font-semibold text-[13px] truncate">{n.title}</span>
                      <span className={`px-1.5 py-0.5 rounded-full text-[9px] font-bold flex-shrink-0 ${ACTION_COLORS[n.action] || 'bg-t3/15 text-t3'}`}>
                        {n.action?.replace(/_/g, ' ')}
                      </span>
                    </div>
                    <p className="text-[12px] text-t2 truncate">{n.message}</p>
                    <div className="flex items-center gap-2 mt-1">
                      <span className="text-[10px] text-t3">{timeAgo(n.created_at)}</span>
                      {n.triggered_by_name && <span className="text-[10px] text-t3">by {n.triggered_by_name}</span>}
                    </div>
                  </div>
                  <div className="flex gap-1 items-center flex-shrink-0 opacity-0 group-hover:opacity-100 transition-opacity" onClick={(e) => e.stopPropagation()}>
                    {!n.is_read && (
                      <button className="p-1 rounded text-ac hover:bg-ac/10" title="Mark read" onClick={() => markRead(n.id)}><Icons.Check /></button>
                    )}
                    <button className="p-1 rounded text-rd hover:bg-rd/10" title="Delete" onClick={() => deleteOne(n.id)}><Icons.Trash /></button>
                  </div>
                  {!n.is_read && <span className="w-2 h-2 rounded-full bg-ac flex-shrink-0 mt-2" />}
                </div>

                {/* Expanded detail */}
                {isExpanded && n.detail && (
                  <div className="px-3.5 pb-3.5 pt-0">
                    <div className="bg-s2 rounded-md p-3 border border-bd text-xs">
                      <div className="text-[11px] font-bold text-ac uppercase mb-2">Detail</div>
                      <div className="grid grid-cols-2 gap-x-4 gap-y-1.5">
                        <div><span className="text-t3">Type:</span> <span className="text-t1">{n.type}</span></div>
                        <div><span className="text-t3">Action:</span> <span className="text-t1">{n.action?.replace(/_/g, ' ')}</span></div>
                        {n.entity && <div><span className="text-t3">Entity:</span> <span className="text-t1">{n.entity}</span></div>}
                        {n.entity_id && <div><span className="text-t3">Entity ID:</span> <span className="text-t1 font-mono">{n.entity_id}</span></div>}
                        {n.triggered_by_name && <div><span className="text-t3">Triggered by:</span> <span className="text-t1">{n.triggered_by_name} (@{n.triggered_by_username})</span></div>}
                        <div><span className="text-t3">Time:</span> <span className="text-t1">{n.created_at ? new Date(n.created_at).toLocaleString() : ''}</span></div>
                      </div>
                      {/* Render detail object */}
                      {typeof n.detail === 'object' && Object.keys(n.detail).length > 0 && (
                        <div className="mt-2.5 pt-2.5 border-t border-bd">
                          <div className="text-[11px] font-bold text-t2 uppercase mb-1.5">Snapshot</div>
                          {Object.entries(n.detail).map(([key, val]) => {
                            if (val && typeof val === 'object' && !Array.isArray(val)) {
                              return (
                                <div key={key} className="mb-2">
                                  <div className="text-[10px] font-semibold text-ac mb-1">{key}</div>
                                  <div className="bg-bg rounded p-2 space-y-0.5">
                                    {Object.entries(val).map(([k, v]) => (
                                      <div key={k} className="flex gap-2">
                                        <span className="text-t3 min-w-[80px]">{k}:</span>
                                        <span className="text-t1 break-all">{v === null ? '—' : typeof v === 'object' ? JSON.stringify(v) : String(v)}</span>
                                      </div>
                                    ))}
                                  </div>
                                </div>
                              );
                            }
                            return (
                              <div key={key} className="flex gap-2 mb-0.5">
                                <span className="text-t3 min-w-[80px]">{key}:</span>
                                <span className="text-t1 break-all">{val === null ? '—' : String(val)}</span>
                              </div>
                            );
                          })}
                        </div>
                      )}
                    </div>
                  </div>
                )}
              </div>
            );
          })
        )}

        {/* Load more */}
        {hasMore && notifications.length > 0 && (
          <div className="text-center py-3 border-t border-bd">
            <button className="text-ac text-xs font-semibold hover:underline" onClick={() => fetchNotifications(false)} disabled={loading}>
              {loading ? 'Loading...' : 'Load more'}
            </button>
          </div>
        )}
      </div>

      {/* Delete All Confirm */}
      <Confirm open={deleteAllCfm} onClose={() => setDeleteAllCfm(false)} icon="🗑️" title="Delete All Notifications?"
        desc="This will remove all notifications from your view."
        cStyle="d" cLabel="Yes, Delete All"
        details={[{ i: '⚠️', t: 'Notifications will be hidden from your view' }, { i: '💾', t: 'Backend log backup is not affected' }]}
        onConfirm={deleteAll}
      />
    </div>
  );
}
