import { useState, useEffect, useRef } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { LayoutDashboard, ClipboardList, Search, MessageSquare, Clock } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { StatCard } from '@/components/shared/StatCard';
import { Skeleton } from '@/components/ui/skeleton';
import { fetchMaterials } from '@/services/materialService';
import { fetchSearchResults } from '@/services/searchService';
import { fetchContactLogs } from '@/services/contactLogService';
import { fetchStandardizationSuccessSummary } from '@/services/standardizedService';
import { formatDate } from '@/lib/dateUtils';
import type { ProcurementMaterial, SearchResult, ContactLog } from '@/types';

interface ActivityItem {
  time: string;
  content: string;
  iconType: 'message-sent' | 'message-skipped' | 'search';
}

interface DashboardLocationState {
  focusSection?: string;
  focusNonce?: number;
}

const RECENT_ACTIVITY_SECTION = 'recent-activity';

export default function Dashboard() {
  const [loading, setLoading] = useState(true);
  const [highlightRecentActivity, setHighlightRecentActivity] = useState(false);
  const [materials, setMaterials] = useState<ProcurementMaterial[]>([]);
  const [searchResults, setSearchResults] = useState<SearchResult[]>([]);
  const [contactLogs, setContactLogs] = useState<ContactLog[]>([]);
  const [standardizedCount, setStandardizedCount] = useState(0);
  const navigate = useNavigate();
  const location = useLocation();
  const recentActivityRef = useRef<HTMLDivElement | null>(null);
  const focusState = location.state as DashboardLocationState | null;

  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const [mats, srs, cls, standardizationSummary] = await Promise.all([
          fetchMaterials(),
          fetchSearchResults(),
          fetchContactLogs(),
          fetchStandardizationSuccessSummary().catch((error) => {
            console.warn('Dashboard standardization summary load error:', error);
            return { totalCount: 0, countByBatchId: {} };
          }),
        ]);
        if (!cancelled) {
          setMaterials(mats);
          setSearchResults(srs);
          setContactLogs(cls);
          setStandardizedCount(standardizationSummary.totalCount);
        }
      } catch (err) {
        console.error('Dashboard data load error:', err);
      } finally {
        if (!cancelled) setLoading(false);
      }
    })();
    return () => { cancelled = true; };
  }, []);

  useEffect(() => {
    if (loading || focusState?.focusSection !== RECENT_ACTIVITY_SECTION) {
      return;
    }

    const scrollTimer = window.setTimeout(() => {
      recentActivityRef.current?.scrollIntoView({
        behavior: 'smooth',
        block: 'start',
        inline: 'nearest',
      });
      setHighlightRecentActivity(true);
      navigate(location.pathname, { replace: true });
    }, 80);

    const highlightTimer = window.setTimeout(() => {
      setHighlightRecentActivity(false);
    }, 1800);

    return () => {
      window.clearTimeout(scrollTimer);
      window.clearTimeout(highlightTimer);
    };
  }, [focusState?.focusNonce, focusState?.focusSection, loading, location.pathname, navigate]);

  const sentCount = contactLogs.filter(l => l.status === 'sent').length;

  // batch summary
  const batchIds = [...new Set(materials.map(m => m.batch_id))];
  const batchSummary = batchIds.map(bid => ({
    batch_id: bid,
    count: materials.filter(m => m.batch_id === bid).length,
    created_at: materials.filter(m => m.batch_id === bid).sort((a, b) => a.created_at.localeCompare(b.created_at))[0]?.created_at || '',
  }));

  // activity timeline
  const activities: ActivityItem[] = [
    ...searchResults.map(sr => ({
      time: sr.created_at,
      content: `搜索 "${sr.keyword}" 找到商品: ${sr.title}`,
      iconType: 'search' as const,
    })),
    ...contactLogs.map(cl => ({
      time: cl.created_at,
      content: `${cl.status === 'sent' ? '已发送消息' : '跳过联系'} - ${cl.merchant_name}`,
      iconType: (cl.status === 'sent' ? 'message-sent' : 'message-skipped') as 'message-sent' | 'message-skipped',
    })),
  ].sort((a, b) => b.time.localeCompare(a.time)).slice(0, 10);

  if (loading) {
    return (
      <div className="space-y-6">
        <div className="grid grid-cols-4 gap-4">
          {[1,2,3,4].map(i => <Skeleton key={i} className="h-24" />)}
        </div>
        <Skeleton className="h-64" />
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        <StatCard title="原始资料总数" value={materials.length} icon={<ClipboardList className="h-5 w-5" />} />
        <StatCard title="已标准化" value={standardizedCount} icon={<LayoutDashboard className="h-5 w-5" />} />
        <StatCard title="搜索结果数" value={searchResults.length} icon={<Search className="h-5 w-5" />} />
        <StatCard title="已联系商家" value={sentCount} icon={<MessageSquare className="h-5 w-5" />} />
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <Card className="lg:col-span-2">
          <CardHeader className="pb-3">
            <CardTitle className="text-base font-semibold">最近批次概览</CardTitle>
          </CardHeader>
          <CardContent>
            <table className="w-full text-sm">
              <thead>
                <tr className="table-header text-left">
                  <th className="p-2.5 rounded-tl-md text-xs font-semibold text-gray-400 uppercase">批次ID</th>
                  <th className="p-2.5 text-xs font-semibold text-gray-400 uppercase">材料数量</th>
                  <th className="p-2.5 rounded-tr-md text-xs font-semibold text-gray-400 uppercase">创建时间</th>
                </tr>
              </thead>
              <tbody>
                {batchSummary.map(b => (
                  <tr
                    key={b.batch_id}
                    className="table-row-stripe table-row-hover cursor-pointer border-b border-border last:border-0"
                    onClick={() => navigate(`/batches?batch=${b.batch_id}`)}
                  >
                    <td className="p-2.5 font-mono text-xs">{b.batch_id}</td>
                    <td className="p-2.5">{b.count}</td>
                    <td className="p-2.5 text-muted-foreground">{formatDate(b.created_at)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </CardContent>
        </Card>

        <Card
          id={RECENT_ACTIVITY_SECTION}
          ref={recentActivityRef}
          tabIndex={-1}
          className={[
            'scroll-mt-6 transition-all duration-500',
            highlightRecentActivity ? 'ring-2 ring-inset ring-primary/70 shadow-[0_16px_36px_-24px_rgba(59,130,246,0.5)]' : '',
          ].join(' ').trim()}
        >
          <CardHeader className="pb-3">
            <CardTitle className="text-base font-semibold flex items-center gap-2">
              <Clock className="h-4 w-4" /> 最近活动
            </CardTitle>
          </CardHeader>
          <CardContent className="max-h-[400px] overflow-y-auto pr-1">
            <ul className="space-y-0">
              {activities.map((a, i) => {
                const isSearch = a.iconType === 'search';
                const isSkipped = a.iconType === 'message-skipped';
                const iconBg = isSearch
                  ? 'bg-blue-100 text-blue-600'
                  : isSkipped
                  ? 'bg-gray-100 text-gray-500'
                  : 'bg-emerald-100 text-emerald-600';
                return (
                  <li key={i} className="flex items-start gap-3 py-3 border-b border-border last:border-0">
                    <div className={`shrink-0 w-9 h-9 rounded-full flex items-center justify-center ${iconBg}`}>
                      {isSearch
                        ? <Search className="h-4 w-4" />
                        : <MessageSquare className="h-4 w-4" />}
                    </div>
                    <div className="min-w-0 flex-1">
                      <p className="text-sm text-foreground leading-snug line-clamp-2">{a.content}</p>
                      <p className="flex items-center gap-1 mt-1 text-xs text-muted-foreground">
                        <Clock className="h-3 w-3 shrink-0" />
                        {formatDate(a.time)}
                      </p>
                    </div>
                  </li>
                );
              })}
            </ul>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
