import { useCallback, useEffect, useState } from 'react';
import { CheckCircle2, Eye, EyeOff, Loader2, Pencil, Plus, Trash2, UserCog, XCircle } from 'lucide-react';
import { toast } from 'sonner';
import { useAuth } from '@/hooks/useAuth';
import { formatDate } from '@/lib/dateUtils';
import { isSupabaseConfigured } from '@/lib/supabase';
import { createAccount, deleteAccount, fetchAccounts, updateAccount } from '@/services/accountService';
import type { ProcurementAccount1688 } from '@/types';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';

interface ProcurementAccountDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onAccountCreated?: (account: ProcurementAccount1688) => void;
  closeOnCreate?: boolean;
}

export function ProcurementAccountDialog({
  open,
  onOpenChange,
  onAccountCreated,
  closeOnCreate = false,
}: ProcurementAccountDialogProps) {
  const { user } = useAuth();
  const [accounts, setAccounts] = useState<ProcurementAccount1688[]>([]);
  const [loading, setLoading] = useState(false);
  const [formDialogOpen, setFormDialogOpen] = useState(false);
  const [editingAccount, setEditingAccount] = useState<ProcurementAccount1688 | null>(null);
  const [formAccountName, setFormAccountName] = useState('');
  const [formPassword, setFormPassword] = useState('');
  const [formRemark, setFormRemark] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [visiblePasswords, setVisiblePasswords] = useState<Set<string>>(new Set());
  const [deleteConfirmId, setDeleteConfirmId] = useState<string | null>(null);

  const loadAccounts = useCallback(async () => {
    if (!user || !isSupabaseConfigured()) {
      setLoading(false);
      return;
    }

    try {
      setLoading(true);
      const data = await fetchAccounts(user.id);
      setAccounts(data);
    } catch {
      toast.error('加载账户列表失败');
    } finally {
      setLoading(false);
    }
  }, [user]);

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

  useEffect(() => {
    if (!open) {
      setFormDialogOpen(false);
      setEditingAccount(null);
      setDeleteConfirmId(null);
      setVisiblePasswords(new Set());
    }
  }, [open]);

  function openCreateDialog() {
    setEditingAccount(null);
    setFormAccountName('');
    setFormPassword('');
    setFormRemark('');
    setFormDialogOpen(true);
  }

  function openEditDialog(account: ProcurementAccount1688) {
    setEditingAccount(account);
    setFormAccountName(account.account_name);
    setFormPassword(account.password);
    setFormRemark(account.remark ?? '');
    setFormDialogOpen(true);
  }

  async function handleSubmit() {
    if (!user) return;

    if (!formAccountName.trim() || !formPassword.trim()) {
      toast.error('账号名和密码不能为空');
      return;
    }

    try {
      setSubmitting(true);
      let createdAccount: ProcurementAccount1688 | null = null;

      if (editingAccount) {
        await updateAccount(editingAccount.id, {
          account_name: formAccountName.trim(),
          password: formPassword.trim(),
          remark: formRemark.trim() || undefined,
        });
        toast.success('账户更新成功');
      } else {
        createdAccount = await createAccount(user.id, {
          account_name: formAccountName.trim(),
          password: formPassword.trim(),
          remark: formRemark.trim() || undefined,
        });
        toast.success('账户添加成功');
      }

      setFormDialogOpen(false);

      if (createdAccount) {
        onAccountCreated?.(createdAccount);
        if (closeOnCreate) {
          onOpenChange(false);
          return;
        }
      }

      await loadAccounts();
    } catch {
      toast.error(editingAccount ? '更新失败' : '添加失败');
    } finally {
      setSubmitting(false);
    }
  }

  async function handleDelete(id: string) {
    try {
      await deleteAccount(id);
      toast.success('账户已删除');
      setDeleteConfirmId(null);
      await loadAccounts();
    } catch {
      toast.error('删除失败');
    }
  }

  function togglePasswordVisibility(id: string) {
    setVisiblePasswords(prev => {
      const next = new Set(prev);
      if (next.has(id)) {
        next.delete(id);
      } else {
        next.add(id);
      }
      return next;
    });
  }

  return (
    <>
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent className="max-h-[85vh] overflow-hidden p-0 sm:max-w-5xl">
          <div className="flex h-full flex-col">
            <DialogHeader className="border-b px-6 py-4 text-left">
              <DialogTitle className="flex items-center gap-2">
                <UserCog className="h-5 w-5 text-blue-600" />
                采购账户管理
              </DialogTitle>
              <DialogDescription>
                管理用于自动询价和自动搜索的 1688 登录账户。
              </DialogDescription>
            </DialogHeader>

            <div className="flex-1 overflow-y-auto px-6 py-5">
              {!isSupabaseConfigured() ? (
                <Card>
                  <CardContent className="py-12 text-center text-muted-foreground">
                    Supabase 未配置，无法使用采购账户管理功能。
                  </CardContent>
                </Card>
              ) : (
                <div className="space-y-4">
                  <div className="flex items-center justify-between gap-4">
                    <div>
                      <h2 className="text-lg font-semibold">1688 采购账户</h2>
                      <p className="text-sm text-muted-foreground">入口已迁移至右上角用户菜单，后续在这里统一管理。</p>
                    </div>
                    <Button onClick={openCreateDialog}>
                      <Plus className="mr-1 h-4 w-4" /> 添加账户
                    </Button>
                  </div>

                  <Card>
                    <CardContent className="p-0">
                      {loading ? (
                        <div className="flex items-center justify-center py-12">
                          <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
                          <span className="ml-2 text-sm text-muted-foreground">加载中…</span>
                        </div>
                      ) : accounts.length === 0 ? (
                        <div className="py-12 text-center text-muted-foreground">
                          <UserCog className="mx-auto mb-3 h-10 w-10 opacity-40" />
                          <p className="text-sm">暂无采购账户，点击右上方按钮添加</p>
                        </div>
                      ) : (
                        <div className="overflow-x-auto">
                          <Table className="min-w-[880px]">
                            <TableHeader>
                              <TableRow>
                                <TableHead>账号名 / 邮箱 / 手机号</TableHead>
                                <TableHead>密码</TableHead>
                                <TableHead>备注</TableHead>
                                <TableHead>登录状态</TableHead>
                                <TableHead>添加时间</TableHead>
                                <TableHead className="text-right">操作</TableHead>
                              </TableRow>
                            </TableHeader>
                            <TableBody>
                              {accounts.map(account => (
                                <TableRow key={account.id}>
                                  <TableCell className="font-medium">{account.account_name}</TableCell>
                                  <TableCell>
                                    <div className="flex items-center gap-1">
                                      <span className="font-mono text-sm">
                                        {visiblePasswords.has(account.id) ? account.password : '••••••••'}
                                      </span>
                                      <Button
                                        variant="ghost"
                                        size="icon"
                                        className="h-7 w-7"
                                        onClick={() => togglePasswordVisibility(account.id)}
                                      >
                                        {visiblePasswords.has(account.id) ? <EyeOff className="h-3.5 w-3.5" /> : <Eye className="h-3.5 w-3.5" />}
                                      </Button>
                                    </div>
                                  </TableCell>
                                  <TableCell className="text-muted-foreground">{account.remark || '—'}</TableCell>
                                  <TableCell>
                                    {account.login_status === 'success' ? (
                                      <Badge variant="outline" className="border-green-200 bg-green-100 text-green-700">
                                        <CheckCircle2 className="mr-1 h-3 w-3" /> 成功
                                      </Badge>
                                    ) : account.login_status === 'failed' ? (
                                      <Tooltip>
                                        <TooltipTrigger asChild>
                                          <Badge variant="outline" className="cursor-help border-red-200 bg-red-100 text-red-700">
                                            <XCircle className="mr-1 h-3 w-3" /> 失败
                                          </Badge>
                                        </TooltipTrigger>
                                        <TooltipContent className="max-w-xs">
                                          <p className="text-xs">{account.login_error || '未知错误'}</p>
                                          {account.login_checked_at && (
                                            <p className="mt-1 text-xs text-muted-foreground">{formatDate(account.login_checked_at)}</p>
                                          )}
                                        </TooltipContent>
                                      </Tooltip>
                                    ) : (
                                      <span className="text-sm text-muted-foreground">—</span>
                                    )}
                                  </TableCell>
                                  <TableCell className="text-muted-foreground">{formatDate(account.created_at)}</TableCell>
                                  <TableCell className="text-right">
                                    <div className="flex items-center justify-end gap-1">
                                      <Tooltip>
                                        <TooltipTrigger asChild>
                                          <Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => openEditDialog(account)}>
                                            <Pencil className="h-4 w-4" />
                                          </Button>
                                        </TooltipTrigger>
                                        <TooltipContent>编辑</TooltipContent>
                                      </Tooltip>
                                      {deleteConfirmId === account.id ? (
                                        <div className="flex items-center gap-1">
                                          <Button variant="destructive" size="sm" onClick={() => handleDelete(account.id)}>确认删除</Button>
                                          <Button variant="ghost" size="sm" onClick={() => setDeleteConfirmId(null)}>取消</Button>
                                        </div>
                                      ) : (
                                        <Tooltip>
                                          <TooltipTrigger asChild>
                                            <Button
                                              variant="ghost"
                                              size="icon"
                                              className="h-8 w-8 text-destructive hover:text-destructive"
                                              onClick={() => setDeleteConfirmId(account.id)}
                                            >
                                              <Trash2 className="h-4 w-4" />
                                            </Button>
                                          </TooltipTrigger>
                                          <TooltipContent>删除</TooltipContent>
                                        </Tooltip>
                                      )}
                                    </div>
                                  </TableCell>
                                </TableRow>
                              ))}
                            </TableBody>
                          </Table>
                        </div>
                      )}
                    </CardContent>
                  </Card>
                </div>
              )}
            </div>
          </div>
        </DialogContent>
      </Dialog>

      <Dialog open={formDialogOpen} onOpenChange={setFormDialogOpen}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>{editingAccount ? '编辑采购账户' : '添加采购账户'}</DialogTitle>
          </DialogHeader>
          <div className="space-y-4 py-2">
            <div className="space-y-2">
              <Label>账号名 / 邮箱 / 手机号 <span className="text-destructive">*</span></Label>
              <Input
                placeholder="请输入 1688 账号名、邮箱或手机号"
                value={formAccountName}
                onChange={event => setFormAccountName(event.target.value)}
              />
            </div>
            <div className="space-y-2">
              <Label>密码 <span className="text-destructive">*</span></Label>
              <Input
                type="password"
                placeholder="请输入密码"
                value={formPassword}
                onChange={event => setFormPassword(event.target.value)}
              />
            </div>
            <div className="space-y-2">
              <Label>备注</Label>
              <Input
                placeholder="可选，如：主账号、子账号等"
                value={formRemark}
                onChange={event => setFormRemark(event.target.value)}
              />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setFormDialogOpen(false)} disabled={submitting}>取消</Button>
            <Button onClick={handleSubmit} disabled={submitting}>
              {submitting && <Loader2 className="mr-1 h-4 w-4 animate-spin" />}
              {editingAccount ? '保存' : '添加'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  );
}