import { useState, useEffect, useMemo } from 'react';
import { toast } from 'sonner';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Skeleton } from '@/components/ui/skeleton';
import { DataTable, Column } from '@/components/shared/DataTable';
import { ExportDialog } from '@/components/shared/ExportDialog';
import { searchFieldClassName } from '@/components/shared/searchFieldStyles';
import { Download, Copy, ExternalLink, RefreshCw, Search, User, Phone, Smartphone, MapPin, Layers, Clock3, Pencil, Check, X } from 'lucide-react';
import { fetchMerchantContacts } from '@/services/merchantService';
import { MerchantContact } from '@/types';
import { formatDate } from '@/lib/dateUtils';
import { useAuth } from '@/hooks/useAuth';

export default function MerchantContacts() {
  const { user } = useAuth();
  const [loading, setLoading] = useState(true);
  const [contacts, setContacts] = useState<MerchantContact[]>([]);
  const [search, setSearch] = useState('');
  const [selected, setSelected] = useState<MerchantContact | null>(null);
  const [selectedKeys, setSelectedKeys] = useState<Set<string>>(new Set());
  const [exportOpen, setExportOpen] = useState(false);
  const [isEditing, setIsEditing] = useState(false);
  const [editDraft, setEditDraft] = useState({
    contact_person: '',
    phone: '',
    mobile: '',
    address: '',
  });

  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const data = await fetchMerchantContacts();
        if (!cancelled) setContacts(data);
      } catch (err) {
        console.error('Failed to fetch merchant contacts:', err);
      } finally {
        if (!cancelled) setLoading(false);
      }
    })();
    return () => { cancelled = true; };
  }, []);

  useEffect(() => {
    if (!selected) {
      setIsEditing(false);
      return;
    }

    setEditDraft({
      contact_person: selected.contact_person || '',
      phone: selected.phone || '',
      mobile: selected.mobile || '',
      address: selected.address || '',
    });
  }, [selected]);

  const filtered = useMemo(() => {
    if (!search) return contacts;
    const s = search.toLowerCase();
    return contacts.filter(m =>
      m.merchant_name.toLowerCase().includes(s) ||
      m.contact_person.toLowerCase().includes(s) ||
      m.phone.includes(s) || m.mobile.includes(s)
    );
  }, [contacts, search]);

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

  const copyContact = (m: MerchantContact) => {
    const text = [m.phone, m.mobile].filter(Boolean).join(' / ');
    navigator.clipboard.writeText(text);
    toast('联系方式已复制到剪贴板');
  };

  const handleEditMerchant = (merchant: MerchantContact) => {
    console.log('edit merchant info', merchant);
    setEditDraft({
      contact_person: merchant.contact_person || '',
      phone: merchant.phone || '',
      mobile: merchant.mobile || '',
      address: merchant.address || '',
    });
    setIsEditing(true);
  };

  const handleSaveMerchant = () => {
    if (!selected) return;

    const nextUpdatedAt = new Date().toISOString();
    const nextSelected = {
      ...selected,
      ...editDraft,
      updated_at: nextUpdatedAt,
      updated_by: user?.displayName ?? user?.username ?? '当前用户',
    };

    setContacts(prev => prev.map(contact => (
      contact.id === selected.id
        ? { ...contact, ...editDraft, updated_at: nextUpdatedAt, updated_by: user?.displayName ?? user?.username ?? '当前用户' }
        : contact
    )));
    setSelected(nextSelected);
    setIsEditing(false);
    toast.success('商家信息已更新');
  };

  const handleCancelEdit = () => {
    if (!selected) return;

    setEditDraft({
      contact_person: selected.contact_person || '',
      phone: selected.phone || '',
      mobile: selected.mobile || '',
      address: selected.address || '',
    });
    setIsEditing(false);
  };

  const handleReset = () => setSearch('');

  const columns: Column<MerchantContact>[] = [
    {
      key: 'merchant_name', label: '商家名称', defaultWidth: 160, nowrap: true,
      render: (v, row) => (
        <a href={row.merchant_url} target="_blank" rel="noopener noreferrer" className="text-primary hover:underline whitespace-nowrap" onClick={e => e.stopPropagation()}>
          {v as string}
        </a>
      ),
    },
    { key: 'contact_person', label: '联系人', defaultWidth: 80 },
    { key: 'phone', label: '电话', defaultWidth: 130, render: v => <span className="whitespace-nowrap">{(v as string) || '-'}</span> },
    { key: 'mobile', label: '手机', defaultWidth: 130, render: v => <span className="whitespace-nowrap">{(v as string) || '-'}</span> },
    { key: 'address', label: '地址', truncate: true, defaultWidth: 160 },
    { key: 'standardized_name', label: '供货商品', truncate: true, defaultWidth: 220, render: v => (v as string) || '-' },
    { key: 'updated_at', label: '更新时间', sortable: true, defaultWidth: 140, render: v => formatDate(v as string) },
    { key: 'updated_by', label: '更新人', defaultWidth: 100, render: v => <span className="whitespace-nowrap">{(v as string) || '-'}</span> },
    {
      key: '_actions', label: '操作', defaultWidth: 80,
      render: (_, row) => (
        <div className="flex gap-1">
          <Button variant="ghost" size="sm" className="text-xs text-blue-500 hover:text-blue-700" onClick={e => { e.stopPropagation(); setSelected(row); }}>详情</Button>
          <Button variant="ghost" size="sm" onClick={e => { e.stopPropagation(); copyContact(row); }}><Copy className="h-3.5 w-3.5" /></Button>
        </div>
      ),
    },
  ];

  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_14rem] gap-x-3 items-center flex-none">
          <span className="text-sm text-muted-foreground">商家/联系人/电话</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-2xl rounded-[24px] border border-slate-200 bg-white/95 p-6 shadow-xl backdrop-blur-md">
          <DialogHeader>
            <DialogTitle className="pr-10 text-xl font-bold text-blue-600">{selected?.merchant_name}</DialogTitle>
          </DialogHeader>
          {selected && (
            <div className="space-y-4 text-sm">
              <div className="grid gap-3 md:grid-cols-2">
                <div className="space-y-2.5">
                  {([
                    ['联系人', selected.contact_person, User],
                    ['电话', selected.phone, Phone],
                    ['手机', selected.mobile, Smartphone],
                    ['地址', selected.address, MapPin],
                  ] as [string, string, typeof User][]).map(([label, value, Icon]) => (
                    <div key={label} className="flex items-start gap-2.5 rounded-2xl border border-slate-200 bg-slate-50/80 px-3 py-2.5">
                      <div className="mt-0.5 rounded-xl bg-white p-1.5 text-slate-500 shadow-sm">
                        <Icon className="h-3.5 w-3.5" />
                      </div>
                      <div className="min-w-0">
                        <div className="text-xs text-slate-400">{label}</div>
                        {isEditing && label === '联系人' ? (
                          <Input
                            value={editDraft.contact_person}
                            onChange={event => setEditDraft(prev => ({ ...prev, contact_person: event.target.value }))}
                            className="mt-1 h-8 border-slate-200 bg-white text-sm text-slate-900"
                          />
                        ) : isEditing && label === '电话' ? (
                          <Input
                            value={editDraft.phone}
                            onChange={event => setEditDraft(prev => ({ ...prev, phone: event.target.value }))}
                            className="mt-1 h-8 border-slate-200 bg-white text-sm text-slate-900"
                          />
                        ) : isEditing && label === '手机' ? (
                          <Input
                            value={editDraft.mobile}
                            onChange={event => setEditDraft(prev => ({ ...prev, mobile: event.target.value }))}
                            className="mt-1 h-8 border-slate-200 bg-white text-sm text-slate-900"
                          />
                        ) : isEditing && label === '地址' ? (
                          <Input
                            value={editDraft.address}
                            onChange={event => setEditDraft(prev => ({ ...prev, address: event.target.value }))}
                            className="mt-1 h-8 border-slate-200 bg-white text-sm text-slate-900"
                          />
                        ) : (
                          <p className="mt-1 break-words text-sm font-medium text-slate-900">{value || '-'}</p>
                        )}
                      </div>
                    </div>
                  ))}
                </div>
                <div className="space-y-2.5">
                  {([
                    ['供货商品', selected.standardized_name || '-', Layers],
                    ['更新时间', formatDate(selected.updated_at), Clock3],
                    ['更新人', selected.updated_by, User],
                  ] as [string, string, typeof Layers][]).map(([label, value, Icon]) => (
                    <div key={label} className="flex items-start gap-2.5 rounded-2xl border border-slate-200 bg-slate-50/80 px-3 py-2.5">
                      <div className="mt-0.5 rounded-xl bg-white p-1.5 text-slate-500 shadow-sm">
                        <Icon className="h-3.5 w-3.5" />
                      </div>
                      <div className="min-w-0">
                        <div className="text-xs text-slate-400">{label}</div>
                        <p className="mt-1 break-words text-sm font-medium text-slate-900">{value || '-'}</p>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
              <div className="flex flex-wrap items-center gap-2 border-t border-slate-200 pt-3">
                <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.merchant_url} target="_blank" rel="noopener noreferrer"><ExternalLink className="mr-1.5 h-3.5 w-3.5" />店铺链接</a>
                </Button>
                <Button
                  size="icon"
                  variant="outline"
                  className="h-9 w-9 rounded-xl border-slate-200 bg-white text-slate-700 hover:bg-blue-50"
                  onClick={() => copyContact(selected)}
                  title="复制联系方式"
                  aria-label="复制联系方式"
                >
                  <Copy className="h-4 w-4" />
                </Button>
                <Button
                  size="sm"
                  variant="outline"
                  className="h-9 rounded-xl border-slate-200 bg-slate-100 px-3.5 text-xs text-slate-700 hover:bg-blue-50"
                  onClick={() => handleEditMerchant(selected)}
                  disabled={isEditing}
                >
                  <Pencil className="mr-1.5 h-3.5 w-3.5" />编辑信息
                </Button>
                {isEditing && (
                  <>
                    <Button
                      size="sm"
                      className="h-9 rounded-xl bg-blue-600 px-3.5 text-xs text-white hover:bg-blue-700"
                      onClick={handleSaveMerchant}
                    >
                      <Check className="mr-1.5 h-3.5 w-3.5" />保存
                    </Button>
                    <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-slate-50"
                      onClick={handleCancelEdit}
                    >
                      <X className="mr-1.5 h-3.5 w-3.5" />取消
                    </Button>
                  </>
                )}
              </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: 'merchant_name', label: '商家名称', group: '基础字段' },
          { key: 'contact_person', label: '联系人', group: '基础字段' },
          { key: 'phone', label: '电话', group: '基础字段' },
          { key: 'mobile', label: '手机', group: '基础字段' },
          { key: 'address', label: '地址', group: '基础字段' },
          { key: 'standardized_name', label: '供货商品', group: '基础字段' },
          { key: 'updated_at', label: '更新时间', group: '基础字段' },
          { key: 'updated_by', label: '更新人', group: '基础字段' },
          { key: 'merchant_url', label: '店铺链接', group: '扩展字段', defaultChecked: false },
          { key: 'contact_page_url', label: '联系页面', group: '扩展字段', defaultChecked: false },
          { key: 'source_offer_url', label: '来源商品链接', group: '扩展字段', defaultChecked: false },
          { key: 'created_at', label: '创建时间', group: '扩展字段', defaultChecked: false },
        ]}
      />
    </div>
  );
}
