import { useState, useEffect, useMemo } from 'react';
import { useSubheader } from '@/components/layout/LayoutSubheaderContext';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { BatchIdCombobox } from '@/components/shared/BatchIdCombobox';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Skeleton } from '@/components/ui/skeleton';
import { DataTable, Column } from '@/components/shared/DataTable';
import { StatusBadge } from '@/components/shared/StatusBadge';
import { ExportDialog } from '@/components/shared/ExportDialog';
import { searchFieldClassName } from '@/components/shared/searchFieldStyles';
import { RefreshCw, ExternalLink, Search, Download, Store, Tag, Hash, CalendarClock, MessageSquareText, CircleAlert, MessagesSquare } from 'lucide-react';
import { fetchContactLogs } from '@/services/contactLogService';
import { fetchSearchResults } from '@/services/searchService';
import { fetchCustomerServiceChats } from '@/services/inquiryService';
import { useProcurementBatchOptions } from '@/hooks/useProcurementBatchOptions';
import { ContactLog, ChatMessage, SearchResult, CustomerServiceChat } from '@/types';
import { formatDate } from '@/lib/dateUtils';

const statusTabs = ['all', 'sent', 'skipped', 'error', 'unknown'] as const;
const statusLabels: Record<string, string> = { all: '全部', sent: '已发送', skipped: '已跳过', error: '失败', unknown: '未知' };
const statusBarColors: Record<string, string> = { sent: 'bg-success', skipped: 'bg-muted-foreground', error: 'bg-destructive', unknown: 'bg-accent' };

function normalizeComparableValue(value?: string | null) {
  return String(value ?? '').trim().replace(/\/+$/, '').toLowerCase();
}

function sameComparableValue(left?: string | null, right?: string | null) {
  const normalizedLeft = normalizeComparableValue(left);
  const normalizedRight = normalizeComparableValue(right);
  return Boolean(normalizedLeft) && normalizedLeft === normalizedRight;
}

function findRelatedChat(log: ContactLog | null, chats: CustomerServiceChat[]) {
  if (!log) {
    return null;
  }

  let bestMatch: CustomerServiceChat | null = null;
  let bestScore = 0;

  for (const chat of chats) {
    let score = 0;

    if (sameComparableValue(chat.search_result_id, log.search_result_id)) {
      score = Math.max(score, 100);
    }
    if (sameComparableValue(chat.contact_url, log.contact_url)) {
      score = Math.max(score, 90);
    }
    if (sameComparableValue(chat.product_url, log.offer_url)) {
      score = Math.max(score, 80);
    }
    if (sameComparableValue(chat.product_url, log.final_url)) {
      score = Math.max(score, 70);
    }

    const sameBatch = sameComparableValue(chat.batch_id, log.batch_id);
    const sameMerchant = sameComparableValue(chat.merchant_name, log.merchant_name);
    const sameTitle = sameComparableValue(chat.title, log.title);

    if (sameBatch && sameMerchant) {
      score = Math.max(score, sameTitle ? 65 : 60);
    }

    if (score > bestScore) {
      bestScore = score;
      bestMatch = chat;
    }
  }

  return bestMatch;
}

function ChatBubbles({ messages }: { messages: ChatMessage[] }) {
  return (
    <div className="space-y-2.5">
      {messages.map((m, i) => (
        <div key={i} className={`flex ${m.role === 'self' ? 'justify-end' : m.role === 'system' ? 'justify-center' : 'justify-start'}`}>
          <div className={`max-w-[78%] rounded-2xl px-3.5 py-2.5 text-xs leading-6 shadow-sm ${
            m.role === 'self' ? 'bg-blue-600 text-white' :
            m.role === 'system' ? 'bg-slate-100 text-slate-500 italic' :
            'border border-slate-200 bg-white text-slate-800'
          }`}>
            {m.content}
          </div>
        </div>
      ))}
    </div>
  );
}

export default function ContactLogs() {
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [batchId, setBatchId] = useState('all');
  const [status, setStatus] = useState('all');
  const [selected, setSelected] = useState<ContactLog | null>(null);
  const [selectedKeys, setSelectedKeys] = useState<Set<string>>(new Set());
  const [exportOpen, setExportOpen] = useState(false);
  const [allContactLogs, setAllContactLogs] = useState<ContactLog[]>([]);
  const [allSearchResults, setAllSearchResults] = useState<SearchResult[]>([]);
  const [allChats, setAllChats] = useState<CustomerServiceChat[]>([]);
  const { batchOptions } = useProcurementBatchOptions();

  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const [cls, srs, chats] = await Promise.all([
          fetchContactLogs(),
          fetchSearchResults(),
          fetchCustomerServiceChats(),
        ]);
        if (!cancelled) {
          setAllContactLogs(cls);
          setAllSearchResults(srs);
          setAllChats(chats);
        }
      } catch (err) {
        console.error('ContactLogs data load error:', err);
      } finally {
        if (!cancelled) setLoading(false);
      }
    })();
    return () => { cancelled = true; };
  }, []);

  const filtered = useMemo(() => {
    let d = [...allContactLogs];
    if (batchId !== 'all') d = d.filter(l => l.batch_id === batchId);
    if (status !== 'all') d = d.filter(l => l.status === status);
    if (search) {
      const s = search.toLowerCase();
      d = d.filter(l => l.keyword.toLowerCase().includes(s) || l.merchant_name.toLowerCase().includes(s) || l.title.toLowerCase().includes(s));
    }
    return d;
  }, [allContactLogs, search, batchId, status]);

  const exportData = selectedKeys.size > 0
    ? filtered.filter(r => selectedKeys.has(r.id))
    : filtered;

  // status counts
  const counts = useMemo(() => {
    const base = batchId === 'all' ? allContactLogs : allContactLogs.filter(l => l.batch_id === batchId);
    return {
      all: base.length,
      sent: base.filter(l => l.status === 'sent').length,
      skipped: base.filter(l => l.status === 'skipped').length,
      error: base.filter(l => l.status === 'error').length,
      unknown: base.filter(l => l.status === 'unknown').length,
    };
  }, [allContactLogs, batchId]);

  const handleReset = () => { setSearch(''); setBatchId('all'); setStatus('all'); };

  const { setSubheader } = useSubheader();

  useEffect(() => {
    setSubheader(
      <div>
        <Tabs value={status} onValueChange={setStatus}>
          <TabsList>
            {statusTabs.map(s => (
              <TabsTrigger key={s} value={s}>
                {statusLabels[s]} {counts[s]}
              </TabsTrigger>
            ))}
          </TabsList>
        </Tabs>
        <div className="h-2 rounded-full bg-muted overflow-hidden flex mt-2">
          {(['sent', 'skipped', 'error', 'unknown'] as const).map(s => (
            counts[s] > 0 ? <div key={s} className={`${statusBarColors[s]} h-full`} style={{ width: `${counts[s] / counts.all * 100}%` }} /> : null
          ))}
        </div>
      </div>
    );
    return () => setSubheader(null);
  }, [status, counts, setSubheader]);

  const relatedSearchResult = useMemo(
    () => (selected ? allSearchResults.find(r => r.id === selected.search_result_id) ?? null : null),
    [selected, allSearchResults],
  );

  const relatedChat = useMemo(
    () => findRelatedChat(selected, allChats),
    [selected, allChats],
  );

  const columns: Column<ContactLog>[] = [
    { key: 'batch_id', label: '批次ID', sortable: true, defaultWidth: 176, render: v => <span className="font-mono text-xs text-muted-foreground whitespace-nowrap">{v as string}</span> },
    { key: 'keyword', label: '搜索关键词', defaultWidth: 130 },
    { key: 'title', label: '商品标题', truncate: true, defaultWidth: 200 },
    { key: 'merchant_name', label: '商家名称', defaultWidth: 150, nowrap: true },
    { key: 'message_sent', label: '发送消息', truncate: true, defaultWidth: 160, render: v => (v as string) || '-' },
    { key: 'status', label: '状态', defaultWidth: 80, render: v => <StatusBadge status={v as string} /> },
    { key: 'reason', label: '原因', truncate: true, defaultWidth: 120, render: (v, row) => (row.status === 'error' || row.status === 'skipped') ? (v as string) : '-' },
    { key: 'conversation_code', label: '会话code', defaultWidth: 120, render: v => v ? <span className="font-mono text-xs">{v as string}</span> : '-' },
    { key: 'created_at', label: '时间', sortable: true, defaultWidth: 140, render: v => formatDate(v as string) },
    {
      key: '_actions', label: '操作', defaultWidth: 60,
      render: (_, row) => (
        <Button variant="ghost" size="sm" className="text-xs text-blue-500 hover:text-blue-700" onClick={e => { e.stopPropagation(); setSelected(row); }}>
          详情
        </Button>
      ),
    },
  ];

  return (
    <div className="h-full flex flex-col">
      {/* 搜索栏 */}
      <div className="mb-3 shrink-0 flex items-start gap-4 w-full">
        <div className="grid grid-cols-[max-content_12rem_max-content_14rem] gap-x-3 gap-y-2 items-center flex-none">
          <span className="text-sm text-muted-foreground">批次ID</span>
          <BatchIdCombobox value={batchId === 'all' ? '' : batchId} onChange={v => setBatchId(v || 'all')} options={batchOptions} />
          <span className="text-sm text-muted-foreground pl-4">关键词/商家/标题</span>
          <Input placeholder="请输入搜索内容" value={search} onChange={e => setSearch(e.target.value)} className={searchFieldClassName} />
        </div>
        <div className="flex items-center gap-2 shrink-0 self-start ml-auto">
          <Button size="sm" className="h-9"><Search className="h-3.5 w-3.5 mr-1" />查询</Button>
          <Button variant="outline" size="icon" className="h-9 w-9" onClick={handleReset} title="重置">
            <RefreshCw className="h-3.5 w-3.5" />
          </Button>
          <Button variant="outline" size="icon" className="h-9 w-9" onClick={() => setExportOpen(true)} title="导出">
            <Download className="h-3.5 w-3.5" />
          </Button>
        </div>
      </div>

      {/* 分割线 */}
      <div className="border-t border-gray-300 mb-3 shrink-0" />


      {/* 内容区 */}
      {loading ? (
        <div className="space-y-3">
          {Array.from({ length: 5 }).map((_, i) => <Skeleton key={i} className="h-10 w-full" />)}
        </div>
      ) : (
        <div className="flex-1 min-h-0">
          <DataTable columns={columns} data={filtered} loading={false} rowKey={(r) => r.id} onRowClick={(row) => setSelected(row)} selectable selectedKeys={selectedKeys} onSelectionChange={setSelectedKeys} showRowIndex />
        </div>
      )}

      <Dialog open={!!selected} onOpenChange={open => !open && setSelected(null)}>
        <DialogContent className="max-w-3xl max-h-[85vh] overflow-y-auto rounded-[24px] border border-slate-200 bg-white/95 p-6 shadow-xl backdrop-blur-md">
          <DialogHeader>
            <DialogTitle className="text-lg font-bold text-blue-600">联系记录详情</DialogTitle>
          </DialogHeader>
          {selected && (
            <div className="space-y-5 text-sm">
              <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-3">
                {([
                  ['商家名称', selected.merchant_name, Store],
                  ['搜索关键词', selected.keyword, Tag],
                  ['会话code', selected.conversation_code, Hash],
                  ['创建时间', formatDate(selected.created_at), CalendarClock],
                ] as [string, string, typeof Store][]).map(([label, value, Icon]) => (
                  <div key={label} className="rounded-2xl border border-slate-200 bg-slate-50/80 px-3.5 py-3">
                    <div className="flex items-center gap-2 text-slate-400">
                      <Icon className="h-3.5 w-3.5" />
                      <span className="text-xs">{label}</span>
                    </div>
                    <p className="mt-2 break-words text-sm font-medium text-slate-900">{value || '-'}</p>
                  </div>
                ))}
                <div className="rounded-2xl border border-slate-200 bg-slate-50/80 px-3.5 py-3">
                  <div className="flex items-center gap-2 text-slate-400">
                    <MessagesSquare className="h-3.5 w-3.5" />
                    <span className="text-xs">状态</span>
                  </div>
                  <div className="mt-2">
                    <StatusBadge status={selected.status} />
                  </div>
                </div>
              </div>

              {selected.message_sent && (
                <div className="rounded-2xl border border-slate-200 bg-slate-50/80 p-4">
                  <div className="flex items-center gap-2 text-slate-400">
                    <MessageSquareText className="h-3.5 w-3.5" />
                    <span className="text-xs">发送消息</span>
                  </div>
                  <p className="mt-2 rounded-xl bg-white px-3 py-2.5 text-sm leading-6 text-slate-900 shadow-sm">{selected.message_sent}</p>
                </div>
              )}
              {selected.reason && (
                <div className="rounded-2xl border border-rose-200 bg-rose-50/70 p-4">
                  <div className="flex items-center gap-2 text-rose-500">
                    <CircleAlert className="h-3.5 w-3.5" />
                    <span className="text-xs">原因</span>
                  </div>
                  <p className="mt-2 text-sm text-rose-600">{selected.reason}</p>
                </div>
              )}

              <div className="flex flex-wrap items-center gap-2 border-t border-slate-200 pt-1">
                <Button size="sm" variant="outline" className="h-9 rounded-xl border-slate-200 bg-white px-3.5 text-xs text-slate-700 hover:bg-blue-50" asChild>
                  <a href={selected.offer_url} target="_blank" rel="noopener noreferrer"><ExternalLink className="mr-1.5 h-3.5 w-3.5" />商品链接</a>
                </Button>
                {selected.contact_url && (
                  <Button size="sm" variant="outline" className="h-9 rounded-xl border-slate-200 bg-white px-3.5 text-xs text-slate-700 hover:bg-blue-50" asChild>
                    <a href={selected.contact_url} target="_blank" rel="noopener noreferrer"><ExternalLink className="mr-1.5 h-3.5 w-3.5" />旺旺聊天</a>
                  </Button>
                )}
              </div>

              {relatedSearchResult && (
                <div className="rounded-2xl border border-slate-200 bg-white p-4">
                  <h4 className="mb-1 text-sm font-semibold text-blue-600">关联搜索结果</h4>
                  <p className="text-sm text-slate-600">{relatedSearchResult.title}</p>
                </div>
              )}

              {relatedChat && relatedChat.chat_history.length > 0 && (
                <div className="rounded-2xl border border-slate-200 bg-slate-50/70 p-4">
                  <h4 className="mb-3 text-sm font-semibold text-blue-600">聊天记录</h4>
                  <ChatBubbles messages={relatedChat.chat_history} />
                </div>
              )}

              {!relatedChat && selected.status === 'sent' && (
                <div className="rounded-2xl border border-dashed border-slate-200 bg-slate-50/70 p-4 text-sm text-slate-500">
                  暂未匹配到对应的旺旺聊天记录，后续同步完成后会在这里显示。
                </div>
              )}
            </div>
          )}
        </DialogContent>
      </Dialog>
      <ExportDialog
        open={exportOpen}
        onOpenChange={setExportOpen}
        data={exportData}
        totalCount={filtered.length}
        filename={`联系记录_${new Date().toLocaleDateString('zh-CN').replace(/\//g, '-')}.xlsx`}
        columns={[
          { key: 'batch_id', label: '批次ID', group: '基础字段' },
          { key: 'keyword', label: '搜索关键词', group: '基础字段' },
          { key: 'title', label: '商品标题', group: '基础字段' },
          { key: 'merchant_name', label: '商家名称', group: '基础字段' },
          { key: 'message_sent', label: '发送消息', group: '基础字段' },
          { key: 'status', label: '状态', group: '基础字段' },
          { key: 'reason', label: '原因', group: '基础字段' },
          { key: 'conversation_code', label: '会话code', group: '基础字段' },
          { key: 'created_at', label: '时间', group: '基础字段' },
          { key: 'offer_url', label: '商品链接', group: '扩展字段', defaultChecked: false },
          { key: 'contact_url', label: '旺旺聊天链接', group: '扩展字段', defaultChecked: false },
          { key: 'final_url', label: '最终URL', group: '扩展字段', defaultChecked: false },
        ]}
      />
    </div>
  );
}
