'use client';

import { useState, useEffect, useCallback } from 'react';
import { PageLayout } from '@/components/organisms/PageLayout';
import { PageHeader } from '@/components/organisms/PageHeader';
import {
  Link2, Loader2, Edit, Check, Building2, CreditCard,
  ShieldCheck, ShieldAlert, Wallet, AlertTriangle,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { toast } from 'sonner';
import { LoginModal } from './LoginModal';
import { SignupModal } from './SignupModal';
import { BankServiceModal } from './BankServiceModal';
import {
  getIntegrationStatus,
  getAccountLinkUrl,
  getCardLinkUrl,
  getCertificateUrl,
  getRegisteredAccounts,
  getRegisteredCards,
  getCertificateStatus,
  getBalance,
} from './actions';
import type {
  IntegrationStatus,
  RegisteredAccount,
  RegisteredCard,
  CertificateInfo,
} from './types';

export function BarobillIntegration() {
  const [status, setStatus] = useState<IntegrationStatus | null>(null);
  const [accounts, setAccounts] = useState<RegisteredAccount[]>([]);
  const [cards, setCards] = useState<RegisteredCard[]>([]);
  const [certificate, setCertificate] = useState<CertificateInfo | null>(null);
  const [balance, setBalance] = useState<number | null>(null);
  const [loginOpen, setLoginOpen] = useState(false);
  const [signupOpen, setSignupOpen] = useState(false);
  const [bankServiceOpen, setBankServiceOpen] = useState(false);
  const [loadingAction, setLoadingAction] = useState<string | null>(null);

  const loadStatus = useCallback(async () => {
    try {
      const result = await getIntegrationStatus();
      if (result.success && result.data) {
        setStatus(result.data);
      }
    } catch {
      // 상태 조회 실패 시 무시
    }
  }, []);

  const loadDashboardData = useCallback(async () => {
    const [accountsRes, cardsRes, certRes, balanceRes] = await Promise.allSettled([
      getRegisteredAccounts(),
      getRegisteredCards(),
      getCertificateStatus(),
      getBalance(),
    ]);

    if (accountsRes.status === 'fulfilled' && accountsRes.value.success && accountsRes.value.data) {
      setAccounts(accountsRes.value.data.accounts ?? []);
    }
    if (cardsRes.status === 'fulfilled' && cardsRes.value.success && cardsRes.value.data) {
      setCards(cardsRes.value.data.cards ?? []);
    }
    if (certRes.status === 'fulfilled' && certRes.value.success && certRes.value.data) {
      setCertificate(certRes.value.data.certificate ?? null);
    }
    if (balanceRes.status === 'fulfilled' && balanceRes.value.success && balanceRes.value.data) {
      setBalance(balanceRes.value.data.balance ?? null);
    }
  }, []);

  useEffect(() => {
    loadStatus();
    loadDashboardData();
  }, [loadStatus, loadDashboardData]);

  const handleExternalLink = useCallback(async (
    type: 'account' | 'card' | 'certificate',
  ) => {
    setLoadingAction(type);
    try {
      const actionMap = {
        account: getAccountLinkUrl,
        card: getCardLinkUrl,
        certificate: getCertificateUrl,
      };
      const result = await actionMap[type]();
      if (result.success && result.data?.url) {
        window.open(result.data.url, '_blank');
      } else {
        toast.error(result.error || '서비스 페이지 URL 조회에 실패했습니다.');
      }
    } catch {
      toast.error('서비스 페이지 URL 조회 중 오류가 발생했습니다.');
    } finally {
      setLoadingAction(null);
    }
  }, []);

  const hasLogin = !!status?.member?.barobillId;

  // 인증서 만료 30일 이내 경고
  const certExpiringSoon = (() => {
    if (!certificate?.expire_date) return false;
    const expireDate = new Date(certificate.expire_date);
    const now = new Date();
    const diffDays = Math.ceil((expireDate.getTime() - now.getTime()) / (1000 * 60 * 60 * 24));
    return diffDays > 0 && diffDays <= 30;
  })();

  // 잔액 부족 경고 (10,000원 미만)
  const balanceLow = balance !== null && balance < 10000;

  return (
    <PageLayout>
      <PageHeader
        title="바로빌 연동 관리"
        description="바로빌 청구, 장부를 연동합니다."
        icon={Link2}
      />

      <div className="space-y-6">
        {/* ===== 연동 현황 대시보드 ===== */}
        {status?.member && (
          <section>
            <h2 className="text-lg font-semibold mb-3">연동 현황</h2>
            <Card>
              <CardContent className="p-5">
                {/* 회원 정보 */}
                <div className="flex flex-wrap items-center gap-2 mb-4 text-sm">
                  <span className="font-medium">{status.member.barobillId}</span>
                  <span className="text-muted-foreground">|</span>
                  <span>{status.member.corpName || status.member.bizNo}</span>
                  {status.member.corpName && (
                    <>
                      <span className="text-muted-foreground">|</span>
                      <span className="text-muted-foreground">{status.member.bizNo}</span>
                    </>
                  )}
                  <span className="text-muted-foreground">|</span>
                  <Badge variant={status.member.serverMode === 'production' ? 'default' : 'secondary'}>
                    {status.member.serverMode === 'production' ? '운영' : '테스트'}
                  </Badge>
                </div>

                {/* 통계 카드 4개 */}
                <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
                  <div className="flex items-center gap-3 rounded-lg border p-3">
                    <Building2 className="h-5 w-5 text-blue-500 shrink-0" />
                    <div>
                      <p className="text-xs text-muted-foreground">계좌</p>
                      <p className="text-lg font-semibold">{status.accountLinkCount}개</p>
                    </div>
                  </div>
                  <div className="flex items-center gap-3 rounded-lg border p-3">
                    <CreditCard className="h-5 w-5 text-purple-500 shrink-0" />
                    <div>
                      <p className="text-xs text-muted-foreground">카드</p>
                      <p className="text-lg font-semibold">{status.cardCount}개</p>
                    </div>
                  </div>
                  <div className="flex items-center gap-3 rounded-lg border p-3">
                    {certificate?.is_valid ? (
                      <ShieldCheck className="h-5 w-5 text-green-500 shrink-0" />
                    ) : (
                      <ShieldAlert className="h-5 w-5 text-red-500 shrink-0" />
                    )}
                    <div>
                      <p className="text-xs text-muted-foreground">인증서</p>
                      <p className="text-sm font-semibold">
                        {certificate ? (certificate.is_valid ? '유효' : '만료') : '-'}
                      </p>
                      {certificate?.expire_date && (
                        <p className="text-xs text-muted-foreground">
                          만료: {certificate.expire_date}
                        </p>
                      )}
                    </div>
                  </div>
                  <div className="flex items-center gap-3 rounded-lg border p-3">
                    <Wallet className="h-5 w-5 text-amber-500 shrink-0" />
                    <div>
                      <p className="text-xs text-muted-foreground">잔액</p>
                      <p className="text-lg font-semibold">
                        {balance !== null ? `${balance.toLocaleString()}원` : '-'}
                      </p>
                    </div>
                  </div>
                </div>

                {/* P2: 경고 표시 */}
                {(certExpiringSoon || balanceLow) && (
                  <div className="mt-4 space-y-2">
                    {certExpiringSoon && (
                      <div className="flex items-center gap-2 rounded-lg bg-amber-50 border border-amber-200 p-3 text-sm">
                        <AlertTriangle className="h-4 w-4 text-amber-500 shrink-0" />
                        <span>공동인증서가 30일 이내 만료됩니다. (만료일: {certificate?.expire_date})</span>
                        <Button
                          variant="link"
                          size="sm"
                          className="ml-auto text-amber-600 px-0"
                          onClick={() => handleExternalLink('certificate')}
                        >
                          인증서 갱신
                        </Button>
                      </div>
                    )}
                    {balanceLow && (
                      <div className="flex items-center gap-2 rounded-lg bg-red-50 border border-red-200 p-3 text-sm">
                        <AlertTriangle className="h-4 w-4 text-red-500 shrink-0" />
                        <span>바로빌 충전잔액이 부족합니다. (현재: {balance?.toLocaleString()}원)</span>
                      </div>
                    )}
                  </div>
                )}
              </CardContent>
            </Card>
          </section>
        )}

        {/* ===== 등록된 계좌/카드 목록 ===== */}
        {(accounts.length > 0 || cards.length > 0) && (
          <section>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {/* 등록된 계좌 */}
              {accounts.length > 0 && (
                <div>
                  <h2 className="text-lg font-semibold mb-3">
                    등록된 계좌 <Badge variant="secondary">{accounts.length}개</Badge>
                  </h2>
                  <Card>
                    <CardContent className="p-4">
                      <ul className="space-y-2">
                        {accounts.map((acc, idx) => (
                          <li key={idx} className="flex items-center gap-2 text-sm">
                            <Building2 className="h-4 w-4 text-muted-foreground shrink-0" />
                            <span className="font-medium">{acc.bankName}</span>
                            <span className="text-muted-foreground">{acc.bankAccountNum}</span>
                          </li>
                        ))}
                      </ul>
                    </CardContent>
                  </Card>
                </div>
              )}

              {/* 등록된 카드 */}
              {cards.length > 0 && (
                <div>
                  <h2 className="text-lg font-semibold mb-3">
                    등록된 카드 <Badge variant="secondary">{cards.length}개</Badge>
                  </h2>
                  <Card>
                    <CardContent className="p-4">
                      <ul className="space-y-2">
                        {cards.map((card, idx) => (
                          <li key={idx} className="flex items-center gap-2 text-sm">
                            <CreditCard className="h-4 w-4 text-muted-foreground shrink-0" />
                            <span className="font-medium">{card.cardCompanyName}</span>
                            <span className="text-muted-foreground">{card.cardNum}</span>
                            {card.alias && (
                              <span className="text-xs text-muted-foreground">({card.alias})</span>
                            )}
                          </li>
                        ))}
                      </ul>
                    </CardContent>
                  </Card>
                </div>
              )}
            </div>
          </section>
        )}

        {/* ===== 바로빌 연동 ===== */}
        <section>
          <h2 className="text-lg font-semibold mb-3">바로빌 연동</h2>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {/* 바로빌 로그인 정보 */}
            <Card>
              <CardContent className="p-5">
                {hasLogin ? (
                  <>
                    <h3 className="font-semibold mb-3">바로빌 로그인 정보</h3>
                    <div className="space-y-2 mb-4">
                      <div className="flex items-center gap-2 text-sm">
                        <span className="text-muted-foreground w-16 shrink-0">아이디</span>
                        <span className="font-medium">{status?.member?.barobillId}</span>
                      </div>
                      <div className="flex items-center gap-2 text-sm">
                        <span className="text-muted-foreground w-16 shrink-0">비밀번호</span>
                        <span className="font-medium">●●●●●●●●</span>
                        <Badge variant="secondary" className="text-xs">
                          <Check className="h-3 w-3 mr-1" />설정됨
                        </Badge>
                      </div>
                    </div>
                    <Button
                      variant="outline"
                      className="w-full"
                      onClick={() => setLoginOpen(true)}
                    >
                      <Edit className="h-4 w-4 mr-2" />
                      로그인 정보 수정
                    </Button>
                  </>
                ) : (
                  <>
                    <h3 className="font-semibold mb-2">바로빌 회원이신가요?</h3>
                    <p className="text-sm text-muted-foreground mb-4">
                      바로빌 로그인 발급 정보 등록
                    </p>
                    <Button
                      variant="destructive"
                      className="w-full"
                      onClick={() => setLoginOpen(true)}
                    >
                      바로빌 로그인 정보 등록
                    </Button>
                  </>
                )}
              </CardContent>
            </Card>

            {/* 바로빌 회원가입 등록 */}
            <Card>
              <CardContent className="p-5">
                <h3 className="font-semibold mb-2">바로빌 회원이 아니신가요?</h3>
                <p className="text-sm text-muted-foreground mb-4">
                  바로빌 회원가입 발급 등록 가능
                </p>
                <Button
                  variant="destructive"
                  className="w-full"
                  onClick={() => setSignupOpen(true)}
                >
                  바로빌 회원가입 등록
                </Button>
              </CardContent>
            </Card>
          </div>
        </section>

        {/* ===== 계좌 연동 ===== */}
        <section>
          <h2 className="text-lg font-semibold mb-3">계좌 연동</h2>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {/* 은행 빠른조회 서비스 등록 */}
            <Card>
              <CardContent className="p-5">
                <div className="flex items-center gap-2 mb-2">
                  <h3 className="font-semibold">은행 빠른조회 서비스 등록</h3>
                  {status && status.bankServiceCount > 0 && (
                    <Badge variant="secondary">{status.bankServiceCount}개</Badge>
                  )}
                </div>
                <ul className="text-sm text-muted-foreground mb-4 space-y-1">
                  <li>— 전 은행 인터넷뱅킹가입 필수</li>
                  <li>— 빠른조회/공과서비스 가입</li>
                  <li>— 조회용 계좌 등록</li>
                </ul>
                <Button
                  variant="destructive"
                  className="w-full"
                  onClick={() => setBankServiceOpen(true)}
                >
                  은행 빠른조회 서비스 등록
                </Button>
              </CardContent>
            </Card>

            {/* 계좌 연동 등록 */}
            <Card>
              <CardContent className="p-5">
                <div className="flex items-center gap-2 mb-2">
                  <h3 className="font-semibold">계좌 연동 등록</h3>
                  {status && status.accountLinkCount > 0 && (
                    <Badge variant="secondary">{status.accountLinkCount}개</Badge>
                  )}
                </div>
                <ul className="text-sm text-muted-foreground mb-4 space-y-1">
                  <li>— 바로빌에 연동되어있는 계좌 등록</li>
                  <li>— 조회 가능 (실시간/주기적)</li>
                </ul>
                <Button
                  variant="destructive"
                  className="w-full"
                  onClick={() => handleExternalLink('account')}
                  disabled={loadingAction === 'account'}
                >
                  {loadingAction === 'account' ? (
                    <><Loader2 className="h-4 w-4 mr-2 animate-spin" />이동 중...</>
                  ) : '계좌 연동 등록'}
                </Button>
              </CardContent>
            </Card>
          </div>
        </section>

        {/* ===== 카드 연동 & 공인인증서 등록 ===== */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          {/* 카드 연동 */}
          <section>
            <h2 className="text-lg font-semibold mb-3">카드 연동</h2>
            <Card>
              <CardContent className="p-5">
                <h3 className="font-semibold mb-2">카드 연동 등록</h3>
                <ul className="text-sm text-muted-foreground mb-4 space-y-1">
                  <li>— 바로빌에 연동 카드 정보 등록</li>
                  <li>— 카드사/비밀디카번/번호 입력</li>
                </ul>
                <Button
                  variant="destructive"
                  className="w-full"
                  onClick={() => handleExternalLink('card')}
                  disabled={loadingAction === 'card'}
                >
                  {loadingAction === 'card' ? (
                    <><Loader2 className="h-4 w-4 mr-2 animate-spin" />이동 중...</>
                  ) : '카드 연동 등록'}
                </Button>
              </CardContent>
            </Card>
          </section>

          {/* 공인인증서 등록 */}
          <section>
            <h2 className="text-lg font-semibold mb-3">공인인증서 등록</h2>
            <Card>
              <CardContent className="p-5">
                <h3 className="font-semibold mb-2">세금계산서용 공인인증서 등록</h3>
                <ul className="text-sm text-muted-foreground mb-4 space-y-1">
                  <li>— 팩스 세금계산서 연동 등록</li>
                  <li>— 범용 공인인증서만 등록 가능 (전자발급용으로도 가능)</li>
                </ul>
                <Button
                  variant="destructive"
                  className="w-full"
                  onClick={() => handleExternalLink('certificate')}
                  disabled={loadingAction === 'certificate'}
                >
                  {loadingAction === 'certificate' ? (
                    <><Loader2 className="h-4 w-4 mr-2 animate-spin" />이동 중...</>
                  ) : '공인인증서 등록'}
                </Button>
              </CardContent>
            </Card>
          </section>
        </div>
      </div>

      {/* 모달 */}
      <LoginModal
        open={loginOpen}
        onOpenChange={setLoginOpen}
        onSuccess={loadStatus}
      />
      <SignupModal
        open={signupOpen}
        onOpenChange={setSignupOpen}
        onSuccess={loadStatus}
      />
      <BankServiceModal
        open={bankServiceOpen}
        onOpenChange={setBankServiceOpen}
      />
    </PageLayout>
  );
}
