'use client';

import { useState } from 'react';
import { AlertTriangle, CheckCircle } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { getPresetStyle } from '@/lib/utils/status-config';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { cn } from '@/lib/utils';
import { CreditSignal } from './CreditSignal';
import { RiskRadarChart } from './RiskRadarChart';
import type { CreditAnalysisData } from './types';
import { CREDIT_LEVEL_CONFIG } from './types';

interface CreditAnalysisDocumentProps {
  data: CreditAnalysisData;
  onApprove?: () => void;
}

export function CreditAnalysisDocument({
  data,
  onApprove,
}: CreditAnalysisDocumentProps) {
  const levelConfig = CREDIT_LEVEL_CONFIG[data.creditLevel];
  const [activeTab, setActiveTab] = useState('shortTermOverdue');

  // 탭 콘텐츠 렌더링
  const renderTabContent = (content: string | null, emptyMessage: string) => {
    if (content) {
      return <p className="text-sm text-gray-700">{content}</p>;
    }
    return (
      <div className="text-center py-4">
        <p className="text-sm text-gray-500">▲ {emptyMessage}</p>
      </div>
    );
  };

  return (
    <div className="bg-white p-8 min-h-full">
      {/* 헤더 */}
      <div className="flex items-center justify-between border-b pb-4 mb-6">
        <div className="flex items-center gap-2">
          <div className="w-8 h-8 bg-green-500 rounded flex items-center justify-center">
            <span className="text-white font-bold text-sm">S</span>
          </div>
          <h1 className="text-lg font-semibold">
            SAM 기업 신용분석 리포트
          </h1>
        </div>
        <span className="text-sm text-gray-500">
          {data.evaluationDate}
        </span>
      </div>

      <div className="space-y-6">
        {/* 기업 정보 */}
        <div className="text-center">
          <Badge variant="outline" className={`mb-2 ${getPresetStyle('info')}`}>
            신규거래 신용정보 조회
          </Badge>
          <h2 className="text-xl font-bold text-gray-800 mt-2">
            - 기업 신용 분석 -
          </h2>
          <p className="text-sm text-gray-600 mt-2">
            사업자번호: {data.businessNumber} | {data.companyName} | 거래기준일: {data.evaluationDate.split(' ')[0]}
          </p>
          <p className="text-xs text-gray-500 mt-1">
            조회일자: {data.queryDate}
          </p>
        </div>

        {/* 자료 효력기간 안내 */}
        <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
          <div className="flex items-start gap-2">
            <AlertTriangle className="w-5 h-5 text-yellow-600 flex-shrink-0 mt-0.5" />
            <div className="text-sm">
              <p className="font-semibold text-yellow-800">자료 효력기간 안내</p>
              <p className="text-yellow-700 mt-1">
                본 보고서(신용분석 6개월 {data.evaluationDate}) 자료는 기준일 당시의 시점이며, 이후 발생한 신용상태의 변동은 반영되지 않았음을 알려드립니다. 신용분석 결과에 의한 거래 관련 판단 및 결정에 대해서는 본사에서 책임지지 않습니다.
              </p>
            </div>
          </div>
        </div>

        {/* 종합 신용 신호등 & 리스크 프로필 */}
        <div className="grid md:grid-cols-2 gap-6">
          {/* 종합 신용 신호등 */}
          <div className="bg-gray-50 rounded-lg p-6">
            <h3 className="text-lg font-semibold text-gray-800 mb-4 text-center">
              종합 신용 신호등
            </h3>
            <CreditSignal
              level={data.creditLevel}
              taxStatus={data.taxStatus}
            />
            <div className="mt-4 text-center">
              <Button variant="outline" size="sm" className="text-blue-600 border-blue-300">
                유료 상세 분석 제공받기
              </Button>
            </div>
          </div>

          {/* 신용 리스크 프로필 */}
          <div className="bg-gray-50 rounded-lg p-6">
            <RiskRadarChart data={data.riskProfile} creditDetailInfo={data.creditDetailInfo} />
          </div>
        </div>

        {/* 신용 상세 정보 - 탭 */}
        <div className="border rounded-lg p-4">
          <h3 className="text-lg font-semibold text-gray-800 mb-4 text-center">
            신용 상세 정보
          </h3>
          <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
            <TabsList className="grid w-full grid-cols-4">
              <TabsTrigger value="shortTermOverdue" className="text-xs sm:text-sm">
                단기연체정보
              </TabsTrigger>
              <TabsTrigger value="creditJudgment" className="text-xs sm:text-sm">
                신용도판단정보
              </TabsTrigger>
              <TabsTrigger value="checkingSuspension" className="text-xs sm:text-sm">
                당좌거래정지
              </TabsTrigger>
              <TabsTrigger value="courtManagement" className="text-xs sm:text-sm">
                법정관리/워크아웃
              </TabsTrigger>
            </TabsList>
            <TabsContent value="shortTermOverdue" className="mt-4">
              {renderTabContent(data.creditDetailTab.shortTermOverdue, '단기연체 정보가 없습니다')}
            </TabsContent>
            <TabsContent value="creditJudgment" className="mt-4">
              {renderTabContent(data.creditDetailTab.creditJudgment, '신용도판단 정보가 없습니다')}
            </TabsContent>
            <TabsContent value="checkingSuspension" className="mt-4">
              {renderTabContent(data.creditDetailTab.checkingSuspension, '당좌거래정지 정보가 없습니다')}
            </TabsContent>
            <TabsContent value="courtManagement" className="mt-4">
              {renderTabContent(data.creditDetailTab.courtManagement, '법정관리/워크아웃 정보가 없습니다')}
            </TabsContent>
          </Tabs>
        </div>

        {/* 거래 승인 판정 */}
        <div className="bg-gray-100 rounded-lg p-4">
          <div className="flex items-center justify-between flex-wrap gap-4">
            <div className="flex items-center gap-6 flex-wrap">
              <div className="text-center">
                <span className="text-sm text-gray-600">거래 승인 판정</span>
                <div className="mt-1">
                  <Badge
                    className={cn(
                      'text-base px-4 py-1',
                      data.approval.safety === '안전'
                        ? 'bg-green-500 hover:bg-green-600'
                        : data.approval.safety === '주의'
                        ? 'bg-yellow-500 hover:bg-yellow-600'
                        : 'bg-red-500 hover:bg-red-600'
                    )}
                  >
                    {data.approval.safety}
                  </Badge>
                </div>
              </div>
              <div className="h-12 border-l border-gray-300 hidden sm:block" />
              <div className="text-center">
                <span className="text-sm text-gray-600">신용등급</span>
                <p className={cn('font-bold', levelConfig.color)}>
                  Level {data.approval.level}
                </p>
              </div>
              <div className="h-12 border-l border-gray-300 hidden sm:block" />
              <div className="text-center">
                <span className="text-sm text-gray-600">거래</span>
                <p className="font-medium text-gray-800">{data.approval.businessType}</p>
              </div>
              <div className="h-12 border-l border-gray-300 hidden sm:block" />
              <div className="text-center">
                <span className="text-sm text-gray-600">외상가능</span>
                <p className={cn(
                  'font-medium',
                  data.approval.creditAvailable ? 'text-green-600' : 'text-red-600'
                )}>
                  {data.approval.creditAvailable ? '가능' : '불가'}
                </p>
              </div>
            </div>
            {onApprove && (
              <Button
                onClick={onApprove}
                className="bg-green-500 hover:bg-green-600 gap-2"
              >
                <CheckCircle className="w-4 h-4" />
                거래 승인 완료
              </Button>
            )}
          </div>
        </div>

        {/* 푸터 */}
        <div className="text-center text-xs text-gray-400 pt-2 border-t">
          <p>SAM Intelligence</p>
          <p>본 신용정보 보고서에 수록된 정보는 특정기업의 신용을 평가하는 자료로 활용될 수 있습니다</p>
        </div>
      </div>
    </div>
  );
}
