import { useState, useEffect, useMemo, useCallback } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import { Label } from '@/components/ui/label';
import { LoaderCircle, Search, UserCog } from 'lucide-react';
import { useAuth } from '@/hooks/useAuth';
import { ProcurementAccountDialog } from '@/components/auth/ProcurementAccountDialog';
import { fetchAccounts } from '@/services/accountService';
import { triggerSearchBatch } from '@/services/automationService';
import type { ProcurementAccount1688, StandardizedMaterial } from '@/types';
import { toast } from 'sonner';

const CONTACT_LIMIT_OPTIONS = [
  { value: '5', label: '5 个商家' },
  { value: '10', label: '10 个商家' },
  { value: '20', label: '20 个商家' },
  { value: 'custom', label: '自定义' },
  { value: '0', label: '全量（不限制）' },
] as const;

type SearchRunMode = 'low_cpu' | 'debug';

interface SearchLaunchDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  mode: 'batch' | 'selected';
  batchId: string;
  selectedItems: StandardizedMaterial[];
  onStarted: (result: { taskIds: string[]; createdCount: number; totalRows: number; batchId: string }) => void;
}

export function SearchLaunchDialog({
  open,
  onOpenChange,
  mode,
  batchId,
  selectedItems,
  onStarted,
}: SearchLaunchDialogProps) {
  const { user } = useAuth();
  const [accounts, setAccounts] = useState<ProcurementAccount1688[]>([]);
  const [selectedAccountId, setSelectedAccountId] = useState('');
  const [contactLimitOption, setContactLimitOption] = useState('5');
  const [customContactLimit, setCustomContactLimit] = useState('');
  const [runMode, setRunMode] = useState<SearchRunMode>('low_cpu');
  const [loading, setLoading] = useState(false);
  const [starting, setStarting] = useState(false);
  const [accountManagerOpen, setAccountManagerOpen] = useState(false);

  const loadAccounts = useCallback(async () => {
    if (!user?.id) {
      setAccounts([]);
      setLoading(false);
      return [] as ProcurementAccount1688[];
    }

    try {
      setLoading(true);
      const data = await fetchAccounts(user.id);
      setAccounts(data);
      setSelectedAccountId(current => (
        current && !data.some(account => account.id === current)
          ? ''
          : current
      ));
      return data;
    } catch (err) {
      toast.error(`加载账户失败: ${err instanceof Error ? err.message : String(err)}`);
      return [] as ProcurementAccount1688[];
    } finally {
      setLoading(false);
    }
  }, [user?.id]);

  useEffect(() => {
    if (open) {
      void loadAccounts();
    }
  }, [open, loadAccounts]);

  useEffect(() => {
    if (!open) {
      setSelectedAccountId('');
      setContactLimitOption('5');
      setCustomContactLimit('');
      setRunMode('low_cpu');
      setAccountManagerOpen(false);
    }
  }, [open]);

  const selectedAccount = useMemo(
    () => accounts.find(a => a.id === selectedAccountId),
    [accounts, selectedAccountId],
  );

  const contactLimit = useMemo(() => {
    if (contactLimitOption === 'custom') {
      const n = Number.parseInt(customContactLimit, 10);
      return Number.isNaN(n) || n <= 0 ? null : n;
    }
    return Number.parseInt(contactLimitOption, 10);
  }, [contactLimitOption, customContactLimit]);

  const contactLimitLabel = useMemo(() => {
    if (contactLimitOption === '0') return '全量（不限制）';
    if (contactLimitOption === 'custom') {
      return contactLimit != null ? `${contactLimit} 个商家` : '请输入数量';
    }
    return `${contactLimitOption} 个商家`;
  }, [contactLimitOption, contactLimit]);

  const isCustomInvalid = contactLimitOption === 'custom' && contactLimit == null;

  const rowCount = mode === 'batch' ? undefined : selectedItems.length;
  const materialIds = mode === 'selected'
    ? selectedItems.map(item => item.material_id).filter(Boolean)
    : undefined;

  // When mode is 'selected', derive the actual batch_id from selected items.
  // The page-level batchId filter may be 'all' (all batches), but后端搜索任务仍需要真实批次 ID。
  const effectiveBatchId = useMemo(() => {
    if (mode === 'selected' && selectedItems.length > 0) {
      return selectedItems[0].batch_id;
    }
    return batchId;
  }, [mode, selectedItems, batchId]);

  const pipelineSummary = '内置固定搜索轮次';

  async function handleStart() {
    if (!selectedAccountId) {
      toast.error('请选择一个 1688 账户');
      return;
    }
    if (isCustomInvalid) {
      toast.error('请输入有效的商家数量');
      return;
    }

    setStarting(true);
    try {
      const result = await triggerSearchBatch({
        batch_id: effectiveBatchId,
        material_ids: materialIds,
        account_id: selectedAccountId,
        contact_limit: contactLimit ?? 0,
        headless: runMode === 'low_cpu',
        resource_profile: runMode,
      });
      toast.success(`已创建搜索任务，包含 ${result.totalRows} 条物料`);
      onOpenChange(false);
      onStarted({
        taskIds: result.taskIds,
        createdCount: result.createdCount,
        totalRows: result.totalRows,
        batchId: effectiveBatchId,
      });
    } catch (err) {
      toast.error(`启动失败: ${err instanceof Error ? err.message : String(err)}`);
    } finally {
      setStarting(false);
    }
  }

  function handleAccountManagerOpenChange(nextOpen: boolean) {
    setAccountManagerOpen(nextOpen);
    if (!nextOpen && open) {
      void loadAccounts();
    }
  }

  function handleAccountCreated(account: ProcurementAccount1688) {
    setAccounts(current => [account, ...current.filter(item => item.id !== account.id)]);
    setSelectedAccountId(account.id);
  }

  return (
    <>
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>启动 1688 自动化搜索</DialogTitle>
            <DialogDescription>
              {mode === 'batch'
                ? `将对批次 ${batchId} 下的所有标准化数据行执行 1688 自动化搜索。`
                : `将对选中的 ${selectedItems.length} 条标准化数据执行 1688 自动化搜索。`}
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-2">
            <div>
              <div className="flex items-center justify-between gap-3">
                <label className="text-sm font-medium">选择 1688 账户</label>
                <Button
                  type="button"
                  variant="ghost"
                  size="sm"
                  className="h-8 px-2 text-primary hover:text-primary"
                  onClick={() => setAccountManagerOpen(true)}
                >
                  <UserCog className="mr-1.5 h-4 w-4" />
                  配置账户
                </Button>
              </div>
              {loading ? (
                <div className="mt-1 flex items-center gap-2 text-sm text-muted-foreground">
                  <LoaderCircle className="h-4 w-4 animate-spin" />
                  加载账户中...
                </div>
              ) : (
                <Select value={selectedAccountId} onValueChange={setSelectedAccountId}>
                  <SelectTrigger className="mt-1" disabled={accounts.length === 0}>
                    <SelectValue placeholder="请选择 1688 账户" />
                  </SelectTrigger>
                  <SelectContent>
                    {accounts.length === 0 ? (
                      <SelectItem value="__none" disabled>暂无账户，请点击右侧“配置账户”完成添加</SelectItem>
                    ) : (
                      accounts.map(a => (
                        <SelectItem key={a.id} value={a.id}>
                          {a.account_name}
                          {a.login_status === 'success' ? ' ✅' : a.login_status === 'failed' ? ' ❌' : ''}
                          {a.remark ? ` (${a.remark})` : ''}
                        </SelectItem>
                      ))
                    )}
                  </SelectContent>
                </Select>
              )}
            </div>
            <div>
              <label className="text-sm font-medium">总共搜索商家数量</label>
              <p className="text-xs text-muted-foreground mt-0.5 mb-1">
                每个搜索阶段最多保存的商家数量，阶段之间会累计入库并自动去重
              </p>
              <Select value={contactLimitOption} onValueChange={setContactLimitOption}>
                <SelectTrigger className="mt-1">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {CONTACT_LIMIT_OPTIONS.map(opt => (
                    <SelectItem key={opt.value} value={opt.value}>{opt.label}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
              {contactLimitOption === 'custom' && (
                <Input
                  type="number"
                  min={1}
                  placeholder="请输入商家数量"
                  value={customContactLimit}
                  onChange={e => setCustomContactLimit(e.target.value)}
                  className="mt-2"
                />
              )}
            </div>
            <div>
              <label className="text-sm font-medium">运行模式</label>
              <RadioGroup value={runMode} onValueChange={(value) => setRunMode(value as SearchRunMode)} className="mt-2 grid gap-2">
                <Label className="flex cursor-pointer items-start gap-3 rounded-md border p-3 text-sm">
                  <RadioGroupItem value="low_cpu" className="mt-0.5" />
                  <span>
                    <span className="block font-medium">无头模式</span>
                    <span className="block text-xs text-muted-foreground">减少浏览器渲染、截图和非核心资源开销</span>
                  </span>
                </Label>
                <Label className="flex cursor-pointer items-start gap-3 rounded-md border p-3 text-sm">
                  <RadioGroupItem value="debug" className="mt-0.5" />
                  <span>
                    <span className="block font-medium">可视化调试</span>
                    <span className="block text-xs text-muted-foreground">打开前台浏览器，适合排查页面、登录或验证码问题</span>
                  </span>
                </Label>
              </RadioGroup>
            </div>
            {selectedAccountId && (
              <div className="rounded-md border p-3 text-sm space-y-1">
                <p>
                  <span className="text-muted-foreground">批次：</span>
                  <span className="font-medium">{effectiveBatchId}</span>
                </p>
                <p>
                  <span className="text-muted-foreground">搜索范围：</span>
                  <span className="font-medium">
                    {mode === 'batch' ? '整个批次所有行' : `选中的 ${rowCount} 行`}
                  </span>
                </p>
                <p>
                  <span className="text-muted-foreground">总数：</span>
                  <span className="font-medium">{contactLimitLabel}</span>
                </p>
                <p>
                  <span className="text-muted-foreground">搜索轮次：</span>
                  <span className="font-medium">{pipelineSummary}</span>
                </p>
                <p>
                  <span className="text-muted-foreground">运行模式：</span>
                  <span className="font-medium">{runMode === 'low_cpu' ? '无头模式' : '可视化调试'}</span>
                </p>
                <p>
                  <span className="text-muted-foreground">执行账户：</span>
                  <span className="font-medium">{selectedAccount?.account_name}</span>
                </p>
              </div>
            )}
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => onOpenChange(false)}>取消</Button>
            <Button onClick={handleStart} disabled={!selectedAccountId || starting || isCustomInvalid}>
              {starting ? <LoaderCircle className="h-4 w-4 animate-spin mr-1.5" /> : <Search className="h-4 w-4 mr-1.5" />}
              启动搜索
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <ProcurementAccountDialog
        open={accountManagerOpen}
        onOpenChange={handleAccountManagerOpenChange}
        onAccountCreated={handleAccountCreated}
        closeOnCreate
      />
    </>
  );
}
