import { useState } from "react";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "./ui/dialog";
import { Button } from "./ui/button";
import { Badge } from "./ui/badge";
import { Card, CardContent } from "./ui/card";
import { Separator } from "./ui/separator";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { Label } from "./ui/label";
import { History, CheckCircle } from "lucide-react";

/**
 * 범용 수정 이력 데이터 인터페이스
 */
export interface RevisionData {
  revisionNumber: number;
  revisionDate: string;
  revisionBy: string;
  revisionReason?: string;
  previousData: any;
}

/**
 * 범용 수정 이력 표시 설정
 */
export interface RevisionDisplayConfig {
  title: string; // 다이얼로그 제목 (예: "견적 수정 이력", "품목 수정 이력")
  itemName: string; // 항목 이름 (예: "견적번호", "품목코드")
  formatFields: (data: any) => React.ReactNode; // 각 버전의 주요 필드 표시 렌더링
  formatAmount?: (data: any) => string; // 금액/수량 표시 (선택)
}

interface RevisionHistoryDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  currentData: any;
  currentRevision: number;
  revisions: RevisionData[];
  config: RevisionDisplayConfig;
}

/**
 * 범용 수정 이력 다이얼로그
 * 견적, 품목, 수주 등 모든 엔티티에 사용 가능
 */
export function RevisionHistoryDialog({
  open,
  onOpenChange,
  currentData,
  currentRevision,
  revisions,
  config
}: RevisionHistoryDialogProps) {
  const formatAmount = (amount: number) => {
    return amount?.toLocaleString('ko-KR') || '0';
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-4xl max-h-[80vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <History className="w-5 h-5 text-orange-600" />
            {config.title}
          </DialogTitle>
          <DialogDescription>
            총 <span className="font-semibold text-orange-600">{currentRevision || 0}회</span> 수정되었습니다
          </DialogDescription>
        </DialogHeader>
        
        <div className="space-y-4">
          {/* 현재 버전 */}
          <Card className="border-2 border-blue-500 bg-blue-50/50">
            <CardContent className="pt-6">
              <div className="flex items-start justify-between mb-4">
                <div className="flex-1">
                  <Badge variant="default" className="bg-blue-600 mb-2">
                    <CheckCircle className="w-3 h-3 mr-1" />
                    현재 버전 (V{currentRevision || 0})
                  </Badge>
                  <div className="text-sm text-muted-foreground mt-2">
                    📅 {currentData?.createdAt || currentData?.quoteDate || '-'}
                  </div>
                </div>
                {config.formatAmount && (
                  <div className="text-right">
                    <div className="text-2xl font-bold text-blue-600">
                      {config.formatAmount(currentData)}
                    </div>
                  </div>
                )}
              </div>
              <div className="mt-4">
                {config.formatFields(currentData)}
              </div>
            </CardContent>
          </Card>

          {/* 수정 이력 */}
          {revisions && revisions.length > 0 ? (
            <>
              <Separator className="my-6" />
              <div className="space-y-4">
                <h4 className="font-semibold text-sm text-muted-foreground flex items-center gap-2">
                  <History className="w-4 h-4" />
                  이전 버전 기록 ({revisions.length}건)
                </h4>
                {[...revisions].reverse().map((revision: RevisionData) => (
                  <Card key={revision.revisionNumber} className="bg-gray-50/50">
                    <CardContent className="pt-6">
                      <div className="flex items-start justify-between mb-4">
                        <div className="flex-1">
                          <div className="flex items-center gap-2 mb-2">
                            <Badge variant="outline" className="bg-white">
                              V{revision.revisionNumber - 1} → V{revision.revisionNumber}
                            </Badge>
                            <Badge variant="secondary" className="bg-orange-100 text-orange-700">
                              {revision.revisionNumber}차 수정
                            </Badge>
                          </div>
                          <div className="text-sm text-muted-foreground mb-2">
                            📅 {revision.revisionDate} | 👤 {revision.revisionBy}
                          </div>
                          {revision.revisionReason && (
                            <div className="bg-white p-3 rounded-md border text-sm mt-2">
                              <div className="flex items-start gap-2">
                                <span className="font-semibold text-orange-600">💬 수정 사유:</span>
                                <span className="flex-1">{revision.revisionReason}</span>
                              </div>
                            </div>
                          )}
                        </div>
                        {config.formatAmount && (
                          <div className="text-right ml-4">
                            <div className="text-xl font-semibold">
                              {config.formatAmount(revision.previousData)}
                            </div>
                          </div>
                        )}
                      </div>
                      <div className="pt-3 border-t">
                        {config.formatFields(revision.previousData)}
                      </div>
                    </CardContent>
                  </Card>
                ))}
              </div>
            </>
          ) : (
            <div className="text-center py-8 text-muted-foreground">
              <History className="w-12 h-12 mx-auto mb-3 opacity-20" />
              <p>수정 이력이 없습니다</p>
              <p className="text-sm mt-1">최초 작성된 항목입니다</p>
            </div>
          )}
        </div>

        <DialogFooter>
          <Button onClick={() => onOpenChange(false)}>
            닫기
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

interface RevisionSelectorProps {
  currentRevision: number;
  revisions: RevisionData[];
  selectedRevision: string;
  onRevisionChange: (revision: string) => void;
  itemType?: string; // 예: "견적", "품목", "수주"
}

/**
 * 범용 수정 이력 선택 드롭다운
 * 과거 버전을 조회할 수 있는 UI
 */
export function RevisionSelector({
  currentRevision,
  revisions,
  selectedRevision,
  onRevisionChange,
  itemType = "항목"
}: RevisionSelectorProps) {
  if (currentRevision === 0 || !revisions || revisions.length === 0) {
    return null;
  }

  return (
    <Card className="bg-gradient-to-r from-orange-50 to-yellow-50 border-orange-200">
      <CardContent className="pt-6">
        <div className="flex items-center gap-4">
          <div className="flex items-center gap-2">
            <History className="w-5 h-5 text-orange-600 dark:text-orange-400" />
            <Label className="text-sm font-semibold">수정 이력 조회</Label>
          </div>
          <Select value={selectedRevision} onValueChange={onRevisionChange}>
            <SelectTrigger className="w-[300px]">
              <SelectValue placeholder="버전 선택" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="current">
                <div className="flex items-center gap-2">
                  <CheckCircle className="w-4 h-4 text-green-600 dark:text-green-400" />
                  <span className="font-semibold">현재 버전 (V{currentRevision})</span>
                </div>
              </SelectItem>
              {[...revisions].reverse().map((revision: RevisionData) => (
                <SelectItem key={revision.revisionNumber} value={revision.revisionNumber.toString()}>
                  <div className="flex items-center gap-2">
                    <History className="w-4 h-4 text-orange-600 dark:text-orange-400" />
                    <span>V{revision.revisionNumber - 1} (수정 {revision.revisionNumber}차)</span>
                    <span className="text-xs text-muted-foreground">- {revision.revisionDate}</span>
                  </div>
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
          {selectedRevision !== "current" && (
            <Badge variant="outline" className="bg-orange-100 text-orange-700 border-orange-300 dark:bg-orange-950 dark:text-orange-300 dark:border-orange-800">
              <History className="w-3 h-3 mr-1" />
              과거 버전 조회 중
            </Badge>
          )}
        </div>
        {selectedRevision !== "current" && (
          <div className="mt-3 text-sm text-orange-700 bg-orange-100 p-2 rounded dark:text-orange-200 dark:bg-orange-950/50 dark:border dark:border-orange-800">
            ℹ️ 과거 버전을 조회하고 있습니다. 현재 버전으로 돌아가려면 드롭다운에서 "현재 버전"을 선택하세요.
          </div>
        )}
      </CardContent>
    </Card>
  );
}

/**
 * 수정 차수 뱃지 컴포넌트
 */
interface RevisionBadgeProps {
  currentRevision: number;
}

export function RevisionBadge({ currentRevision }: RevisionBadgeProps) {
  if ((currentRevision || 0) > 0) {
    return (
      <Badge variant="secondary" className="bg-orange-100 text-orange-700 border-orange-300">
        <History className="w-3 h-3 mr-1" />
        {currentRevision}차 수정
      </Badge>
    );
  }
  return <Badge variant="outline" className="bg-gray-50">최초 작성</Badge>;
}

/**
 * 선택된 버전의 데이터를 가져오는 유틸리티 함수
 */
export function getDisplayDataByRevision<T>(
  currentData: T,
  selectedRevision: string,
  revisions?: RevisionData[]
): T & { isHistoricalView?: boolean; viewingRevision?: number } {
  if (selectedRevision === "current") {
    return currentData;
  }
  
  const revisionNumber = parseInt(selectedRevision);
  const revision = revisions?.find(r => r.revisionNumber === revisionNumber);
  
  if (revision) {
    return {
      ...currentData,
      ...revision.previousData,
      isHistoricalView: true,
      viewingRevision: revisionNumber
    };
  }
  
  return currentData;
}