import { useState, useEffect } from "react";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "./ui/dialog";
import { Button } from "./ui/button";
import { Textarea } from "./ui/textarea";
import { Label } from "./ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { Badge } from "./ui/badge";
import { Card, CardContent } from "./ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "./ui/table";
import { Clock, GitBranch, User, Calendar, Tag, ChevronDown, ChevronUp } from "lucide-react";
import { toast } from "sonner@2.0.3";

// 버전 히스토리 타입
export interface VersionHistory {
  id: string;
  versionNumber: number;
  version: string;
  changeDescription: string;
  changedBy: string;
  changedAt: string;
  changeType: 'major' | 'minor' | 'patch';
  tags?: string[];
}

// 화면 버전 정보 타입
export interface ScreenVersion {
  id: string;
  screenName: string;
  screenPath: string;
  version: string;
  versionHistory: VersionHistory[];
  currentVersion: number;
  lastModifiedAt: string;
  lastModifiedBy: string;
}

interface VersionControlDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  screenName: string;
  screenPath: string;
  onConfirm: (changeDescription: string, changeType: 'major' | 'minor' | 'patch', tags: string[]) => void;
  onCancel: () => void;
}

export function VersionControlDialog({
  open,
  onOpenChange,
  screenName,
  screenPath,
  onConfirm,
  onCancel
}: VersionControlDialogProps) {
  const [changeDescription, setChangeDescription] = useState("");
  const [changeType, setChangeType] = useState<'major' | 'minor' | 'patch'>('patch');
  const [tags, setTags] = useState<string[]>([]);
  const [customTag, setCustomTag] = useState("");

  const predefinedTags = [
    "기능추가",
    "버그수정",
    "UI개선",
    "성능개선",
    "리팩토링",
    "문서화"
  ];

  const handleConfirm = () => {
    if (!changeDescription.trim()) {
      toast.error("변경 내용을 입력해주세요.");
      return;
    }
    onConfirm(changeDescription, changeType, tags);
    // 초기화
    setChangeDescription("");
    setChangeType('patch');
    setTags([]);
    setCustomTag("");
  };

  const handleCancel = () => {
    onCancel();
    onOpenChange(false);
    // 초기화
    setChangeDescription("");
    setChangeType('patch');
    setTags([]);
    setCustomTag("");
  };

  const toggleTag = (tag: string) => {
    setTags(prev => 
      prev.includes(tag) 
        ? prev.filter(t => t !== tag)
        : [...prev, tag]
    );
  };

  const addCustomTag = () => {
    if (customTag.trim() && !tags.includes(customTag.trim())) {
      setTags([...tags, customTag.trim()]);
      setCustomTag("");
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-2xl">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <GitBranch className="h-5 w-5 text-blue-600" />
            버전 업데이트
          </DialogTitle>
          <DialogDescription>
            <span className="font-medium">{screenName}</span> 화면의 변경사항을 버전으로 기록하시겠습니까?
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4 py-4">
          {/* 변경 유형 */}
          <div>
            <Label className="flex items-center gap-1 mb-2">
              변경 유형 <span className="text-red-500">*</span>
            </Label>
            <Select value={changeType} onValueChange={(value: any) => setChangeType(value)}>
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="patch">
                  <div className="flex items-center gap-2">
                    <Badge variant="outline" className="bg-green-50 text-green-700 border-green-200">
                      Patch
                    </Badge>
                    <span className="text-sm text-muted-foreground">버그 수정 (0.0.X)</span>
                  </div>
                </SelectItem>
                <SelectItem value="minor">
                  <div className="flex items-center gap-2">
                    <Badge variant="outline" className="bg-blue-50 text-blue-700 border-blue-200">
                      Minor
                    </Badge>
                    <span className="text-sm text-muted-foreground">기능 추가 (0.X.0)</span>
                  </div>
                </SelectItem>
                <SelectItem value="major">
                  <div className="flex items-center gap-2">
                    <Badge variant="outline" className="bg-purple-50 text-purple-700 border-purple-200">
                      Major
                    </Badge>
                    <span className="text-sm text-muted-foreground">대규모 변경 (X.0.0)</span>
                  </div>
                </SelectItem>
              </SelectContent>
            </Select>
          </div>

          {/* 변경 내용 */}
          <div>
            <Label className="flex items-center gap-1 mb-2">
              변경 내용 <span className="text-red-500">*</span>
            </Label>
            <Textarea
              value={changeDescription}
              onChange={(e) => setChangeDescription(e.target.value)}
              placeholder="변경된 내용을 상세히 입력해주세요&#10;예시: 재질별 폭합 섹션 추가, BOM 테이블 레이아웃 개선"
              rows={4}
            />
          </div>

          {/* 태그 선택 */}
          <div>
            <Label className="mb-2 block">태그 (선택사항)</Label>
            <div className="flex flex-wrap gap-2 mb-2">
              {predefinedTags.map(tag => (
                <Badge
                  key={tag}
                  variant={tags.includes(tag) ? "default" : "outline"}
                  className="cursor-pointer"
                  onClick={() => toggleTag(tag)}
                >
                  {tag}
                </Badge>
              ))}
            </div>
            <div className="flex gap-2">
              <input
                type="text"
                value={customTag}
                onChange={(e) => setCustomTag(e.target.value)}
                onKeyPress={(e) => e.key === 'Enter' && addCustomTag()}
                placeholder="커스텀 태그 입력..."
                className="flex-1 h-9 rounded-md border border-input bg-background px-3 py-1 text-sm"
              />
              <Button type="button" variant="outline" size="sm" onClick={addCustomTag}>
                추가
              </Button>
            </div>
            {tags.length > 0 && (
              <div className="flex flex-wrap gap-2 mt-2">
                {tags.map(tag => (
                  <Badge key={tag} variant="secondary" className="gap-1">
                    <Tag className="h-3 w-3" />
                    {tag}
                  </Badge>
                ))}
              </div>
            )}
          </div>
        </div>

        <DialogFooter className="gap-2">
          <Button variant="outline" onClick={handleCancel}>
            취소 (버전 업데이트 안함)
          </Button>
          <Button onClick={handleConfirm}>
            <GitBranch className="h-4 w-4 mr-2" />
            버전 업데이트
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

interface VersionHistoryViewerProps {
  screenName: string;
  versionHistory: VersionHistory[];
  currentVersion: string;
}

export function VersionHistoryViewer({
  screenName,
  versionHistory,
  currentVersion
}: VersionHistoryViewerProps) {
  const [expanded, setExpanded] = useState(false);

  const getChangeTypeBadge = (type: 'major' | 'minor' | 'patch') => {
    switch (type) {
      case 'major':
        return <Badge variant="outline" className="bg-purple-50 text-purple-700 border-purple-200">Major</Badge>;
      case 'minor':
        return <Badge variant="outline" className="bg-blue-50 text-blue-700 border-blue-200">Minor</Badge>;
      case 'patch':
        return <Badge variant="outline" className="bg-green-50 text-green-700 border-green-200">Patch</Badge>;
    }
  };

  if (versionHistory.length === 0) {
    return null;
  }

  return (
    <Card>
      <CardContent className="p-4">
        <div 
          className="flex items-center justify-between cursor-pointer"
          onClick={() => setExpanded(!expanded)}
        >
          <div className="flex items-center gap-2">
            <GitBranch className="h-4 w-4 text-blue-600" />
            <span className="text-sm">버전 히스토리</span>
            <Badge variant="secondary">v{currentVersion}</Badge>
          </div>
          {expanded ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />}
        </div>

        {expanded && (
          <div className="mt-4">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="w-[100px]">버전</TableHead>
                  <TableHead className="w-[80px]">유형</TableHead>
                  <TableHead>변경 내용</TableHead>
                  <TableHead className="w-[120px]">변경자</TableHead>
                  <TableHead className="w-[140px]">변경 일시</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {versionHistory.slice().reverse().map((history) => (
                  <TableRow key={history.id}>
                    <TableCell>
                      <Badge variant="outline">v{history.version}</Badge>
                    </TableCell>
                    <TableCell>{getChangeTypeBadge(history.changeType)}</TableCell>
                    <TableCell>
                      <div>
                        <p className="text-sm">{history.changeDescription}</p>
                        {history.tags && history.tags.length > 0 && (
                          <div className="flex gap-1 mt-1">
                            {history.tags.map((tag, idx) => (
                              <Badge key={idx} variant="secondary" className="text-xs">
                                {tag}
                              </Badge>
                            ))}
                          </div>
                        )}
                      </div>
                    </TableCell>
                    <TableCell className="text-sm text-muted-foreground">
                      {history.changedBy}
                    </TableCell>
                    <TableCell className="text-sm text-muted-foreground">
                      {new Date(history.changedAt).toLocaleString('ko-KR')}
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>
        )}
      </CardContent>
    </Card>
  );
}

// 버전 관리 Hook
export function useVersionControl(screenName: string, screenPath: string) {
  const storageKey = `screen_version_${screenPath}`;
  
  const [screenVersion, setScreenVersion] = useState<ScreenVersion>(() => {
    const saved = localStorage.getItem(storageKey);
    if (saved) {
      return JSON.parse(saved);
    }
    return {
      id: Date.now().toString(),
      screenName,
      screenPath,
      version: "1.0.0",
      versionHistory: [],
      currentVersion: 1,
      lastModifiedAt: new Date().toISOString(),
      lastModifiedBy: "관리자"
    };
  });

  const [isVersionDialogOpen, setIsVersionDialogOpen] = useState(false);
  const [pendingUpdate, setPendingUpdate] = useState<(() => void) | null>(null);

  // localStorage에 저장
  useEffect(() => {
    localStorage.setItem(storageKey, JSON.stringify(screenVersion));
  }, [screenVersion, storageKey]);

  // 버전 업데이트 요청
  const requestVersionUpdate = (updateCallback: () => void) => {
    // 다이얼로그 없이 바로 수정사항만 적용
    updateCallback();
    toast.info("수정사항이 적용되었습니다.");
  };

  // 버전 업데이트 확인
  const confirmVersionUpdate = (
    changeDescription: string,
    changeType: 'major' | 'minor' | 'patch',
    tags: string[]
  ) => {
    const [major, minor, patch] = screenVersion.version.split('.').map(Number);
    let newVersion = "";
    
    if (changeType === 'major') {
      newVersion = `${major + 1}.0.0`;
    } else if (changeType === 'minor') {
      newVersion = `${major}.${minor + 1}.0`;
    } else {
      newVersion = `${major}.${minor}.${patch + 1}`;
    }

    const newHistory: VersionHistory = {
      id: Date.now().toString(),
      versionNumber: screenVersion.currentVersion + 1,
      version: newVersion,
      changeDescription,
      changedBy: "관리자", // TODO: 실제 사용자 정보로 교체
      changedAt: new Date().toISOString(),
      changeType,
      tags
    };

    setScreenVersion({
      ...screenVersion,
      version: newVersion,
      versionHistory: [...screenVersion.versionHistory, newHistory],
      currentVersion: screenVersion.currentVersion + 1,
      lastModifiedAt: new Date().toISOString(),
      lastModifiedBy: "관리자"
    });

    // 대기 중인 업데이트 실행
    if (pendingUpdate) {
      pendingUpdate();
      setPendingUpdate(null);
    }

    setIsVersionDialogOpen(false);
    toast.success(`버전 ${newVersion}으로 업데이트되었습니다.`);
  };

  // 버전 업데이트 취소 (수정만 적용)
  const cancelVersionUpdate = () => {
    // 대기 중인 업데이트 실행 (버전 업데이트 없이)
    if (pendingUpdate) {
      pendingUpdate();
      setPendingUpdate(null);
    }
    
    setIsVersionDialogOpen(false);
    toast.info("버전 업데이트 없이 수정사항만 적용되었습니다.");
  };

  return {
    screenVersion,
    isVersionDialogOpen,
    setIsVersionDialogOpen,
    requestVersionUpdate,
    confirmVersionUpdate,
    cancelVersionUpdate
  };
}