import React, { useState, useEffect } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
import { Label } from "./ui/label";
import { Badge } from "./ui/badge";
import { Textarea } from "./ui/textarea";
import {
  Save,
  FolderOpen,
  Trash2,
  Download,
  Upload,
  FileText,
  Copy,
  CheckCircle2,
} from "lucide-react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
  DialogFooter,
} from "./ui/dialog";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "./ui/alert-dialog";
import { toast } from "sonner@2.0.3";
import type { FormulaRule } from "./contexts/DataContext";

interface RuleTemplate {
  id: string;
  name: string;
  description: string;
  category: string;
  rules: Omit<FormulaRule, 'id' | 'createdAt' | 'updatedAt' | 'createdBy' | 'updatedBy'>[];
  createdAt: string;
  tags: string[];
}

interface RuleTemplateManagerProps {
  currentRules?: FormulaRule[];
  onLoadTemplate: (rules: FormulaRule[]) => void;
}

export function RuleTemplateManager({
  currentRules,
  onLoadTemplate,
}: RuleTemplateManagerProps) {
  const [templates, setTemplates] = useState<RuleTemplate[]>([]);
  const [isOpen, setIsOpen] = useState(false);
  const [isSaveDialogOpen, setIsSaveDialogOpen] = useState(false);
  
  // 템플릿 저장 폼
  const [templateForm, setTemplateForm] = useState({
    name: '',
    description: '',
    category: '',
    tags: '',
  });

  // localStorage에서 템플릿 로드
  useEffect(() => {
    const saved = localStorage.getItem('SAM_RULE_TEMPLATES');
    if (saved) {
      try {
        setTemplates(JSON.parse(saved));
      } catch (error) {
        console.error('템플릿 로드 오류:', error);
      }
    }
  }, []);

  // 템플릿 저장
  const saveTemplates = (newTemplates: RuleTemplate[]) => {
    setTemplates(newTemplates);
    localStorage.setItem('SAM_RULE_TEMPLATES', JSON.stringify(newTemplates));
  };

  // 현재 규칙을 템플릿으로 저장
  const handleSaveTemplate = () => {
    if (!currentRules || currentRules.length === 0) {
      toast.error('저장할 규칙이 없습니다.');
      return;
    }

    if (!templateForm.name.trim()) {
      toast.error('템플릿 이름을 입력해주세요.');
      return;
    }

    // ID와 시간 정보를 제외한 규칙 데이터
    const cleanRules = currentRules.map(rule => {
      const { id, createdAt, updatedAt, createdBy, updatedBy, ...rest } = rule;
      return rest;
    });

    const newTemplate: RuleTemplate = {
      id: `TEMPLATE-${Date.now()}`,
      name: templateForm.name,
      description: templateForm.description,
      category: templateForm.category,
      rules: cleanRules as any,
      createdAt: new Date().toISOString(),
      tags: templateForm.tags.split(',').map(t => t.trim()).filter(t => t),
    };

    saveTemplates([...templates, newTemplate]);
    toast.success(`템플릿 "${newTemplate.name}"이 저장되었습니다.`);
    
    // 폼 초기화
    setTemplateForm({ name: '', description: '', category: '', tags: '' });
    setIsSaveDialogOpen(false);
  };

  // 템플릿 불러오기
  const handleLoadTemplate = (template: RuleTemplate) => {
    const now = new Date().toISOString().split("T")[0];
    const timestamp = Date.now();

    // 템플릿의 규칙들을 새로운 ID로 생성
    const newRules: FormulaRule[] = template.rules.map((rule, index) => ({
      ...rule,
      id: `RULE-${timestamp}-${index}`,
      createdAt: now,
      updatedAt: now,
      createdBy: '관리자',
      updatedBy: '관리자',
    } as FormulaRule));

    onLoadTemplate(newRules);
    toast.success(`템플릿 "${template.name}"을 불러왔습니다. (${newRules.length}개 규칙)`);
    setIsOpen(false);
  };

  // 템플릿 삭제
  const handleDeleteTemplate = (templateId: string) => {
    const template = templates.find(t => t.id === templateId);
    saveTemplates(templates.filter(t => t.id !== templateId));
    toast.success(`템플릿 "${template?.name}"이 삭제되었습니다.`);
  };

  // 템플릿 복사
  const handleCopyTemplate = (template: RuleTemplate) => {
    const copiedTemplate: RuleTemplate = {
      ...template,
      id: `TEMPLATE-${Date.now()}`,
      name: `${template.name} (복사본)`,
      createdAt: new Date().toISOString(),
    };
    saveTemplates([...templates, copiedTemplate]);
    toast.success(`템플릿이 복사되었습니다.`);
  };

  // 템플릿 파일로 내보내기
  const handleExportTemplate = (template: RuleTemplate) => {
    const dataStr = JSON.stringify(template, null, 2);
    const dataBlob = new Blob([dataStr], { type: 'application/json' });
    const url = URL.createObjectURL(dataBlob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `template_${template.name.replace(/\s+/g, '_')}_${Date.now()}.json`;
    link.click();
    URL.revokeObjectURL(url);
    toast.success('템플릿이 파일로 내보내기되었습니다.');
  };

  // 템플릿 파일에서 가져오기
  const handleImportTemplate = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = (e) => {
      try {
        const imported = JSON.parse(e.target?.result as string) as RuleTemplate;
        // 새로운 ID 부여
        imported.id = `TEMPLATE-${Date.now()}`;
        imported.createdAt = new Date().toISOString();
        saveTemplates([...templates, imported]);
        toast.success(`템플릿 "${imported.name}"을 가져왔습니다.`);
      } catch (error) {
        console.error('템플릿 가져오기 오류:', error);
        toast.error('템플릿 파일 형식이 올바르지 않습니다.');
      }
    };
    reader.readAsText(file);
    // 파일 입력 초기화
    event.target.value = '';
  };

  return (
    <div className="flex gap-2">
      {/* 템플릿 저장 버튼 */}
      <Dialog open={isSaveDialogOpen} onOpenChange={setIsSaveDialogOpen}>
        <DialogTrigger asChild>
          <Button 
            variant="outline"
            disabled={!currentRules || currentRules.length === 0}
            className="border-green-500 text-green-700 hover:bg-green-50"
          >
            <Save className="h-4 w-4 mr-2" />
            템플릿 저장
          </Button>
        </DialogTrigger>
        <DialogContent>
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Save className="h-5 w-5" />
              규칙 템플릿 저장
            </DialogTitle>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="bg-blue-50 border border-blue-200 rounded-lg p-3">
              <p className="text-sm text-blue-800">
                📦 현재 선택된 <strong>{currentRules?.length || 0}개의 규칙</strong>을 템플릿으로 저장합니다
              </p>
            </div>
            
            <div>
              <Label>템플릿 이름 *</Label>
              <Input
                value={templateForm.name}
                onChange={(e) => setTemplateForm({ ...templateForm, name: e.target.value })}
                placeholder="예: 스크린용 감기샤프트 전체 규칙"
              />
            </div>

            <div>
              <Label>설명</Label>
              <Textarea
                value={templateForm.description}
                onChange={(e) => setTemplateForm({ ...templateForm, description: e.target.value })}
                placeholder="템플릿에 대한 설명을 입력하세요"
                rows={3}
              />
            </div>

            <div>
              <Label>카테고리</Label>
              <Input
                value={templateForm.category}
                onChange={(e) => setTemplateForm({ ...templateForm, category: e.target.value })}
                placeholder="예: 감기샤프트, 가이드레일, 케이스"
              />
            </div>

            <div>
              <Label>태그 (쉼표로 구분)</Label>
              <Input
                value={templateForm.tags}
                onChange={(e) => setTemplateForm({ ...templateForm, tags: e.target.value })}
                placeholder="예: 스크린, 다단계, 샤프트"
              />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setIsSaveDialogOpen(false)}>
              취소
            </Button>
            <Button onClick={handleSaveTemplate} className="bg-green-600 hover:bg-green-700">
              <Save className="h-4 w-4 mr-2" />
              저장
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 템플릿 불러오기 버튼 */}
      <Dialog open={isOpen} onOpenChange={setIsOpen}>
        <DialogTrigger asChild>
          <Button variant="outline" className="border-blue-500 text-blue-700 hover:bg-blue-50">
            <FolderOpen className="h-4 w-4 mr-2" />
            템플릿 불러오기
          </Button>
        </DialogTrigger>
        <DialogContent className="max-w-4xl max-h-[80vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <FolderOpen className="h-5 w-5" />
              규칙 템플릿 관리
            </DialogTitle>
          </DialogHeader>

          <div className="space-y-4 py-4">
            {/* 파일에서 가져오기 */}
            <div className="flex gap-2">
              <Button
                variant="outline"
                size="sm"
                onClick={() => document.getElementById('template-import')?.click()}
                className="w-full"
              >
                <Upload className="h-4 w-4 mr-2" />
                파일에서 가져오기
              </Button>
              <input
                id="template-import"
                type="file"
                accept=".json"
                onChange={handleImportTemplate}
                className="hidden"
              />
            </div>

            {/* 템플릿 목록 */}
            {templates.length === 0 ? (
              <div className="text-center py-12 text-gray-500">
                <FileText className="h-16 w-16 mx-auto mb-4 opacity-30" />
                <p>저장된 템플릿이 없습니다</p>
                <p className="text-sm mt-2">현재 규칙을 템플릿으로 저장해보세요</p>
              </div>
            ) : (
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                {templates.map((template) => (
                  <Card key={template.id} className="border-2 hover:border-blue-300 transition-colors">
                    <CardHeader className="pb-3">
                      <div className="flex items-start justify-between">
                        <div className="flex-1">
                          <CardTitle className="text-base flex items-center gap-2">
                            <FileText className="h-4 w-4" />
                            {template.name}
                          </CardTitle>
                          {template.category && (
                            <Badge variant="outline" className="mt-1">
                              {template.category}
                            </Badge>
                          )}
                        </div>
                      </div>
                    </CardHeader>
                    <CardContent className="space-y-3">
                      {template.description && (
                        <p className="text-sm text-gray-600">{template.description}</p>
                      )}
                      
                      <div className="flex items-center gap-2 text-xs text-gray-500">
                        <Badge variant="secondary">{template.rules.length}개 규칙</Badge>
                        <span>•</span>
                        <span>{new Date(template.createdAt).toLocaleDateString()}</span>
                      </div>

                      {template.tags.length > 0 && (
                        <div className="flex flex-wrap gap-1">
                          {template.tags.map((tag, idx) => (
                            <Badge key={idx} variant="outline" className="text-xs">
                              #{tag}
                            </Badge>
                          ))}
                        </div>
                      )}

                      <div className="flex gap-2 pt-2 border-t">
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => handleLoadTemplate(template)}
                          className="flex-1 bg-blue-600 text-white hover:bg-blue-700"
                        >
                          <CheckCircle2 className="h-3 w-3 mr-1" />
                          불러오기
                        </Button>
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => handleCopyTemplate(template)}
                          title="복사"
                        >
                          <Copy className="h-3 w-3" />
                        </Button>
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => handleExportTemplate(template)}
                          title="내보내기"
                        >
                          <Download className="h-3 w-3" />
                        </Button>
                        <AlertDialog>
                          <AlertDialogTrigger asChild>
                            <Button variant="outline" size="sm" title="삭제">
                              <Trash2 className="h-3 w-3 text-red-600" />
                            </Button>
                          </AlertDialogTrigger>
                          <AlertDialogContent>
                            <AlertDialogHeader>
                              <AlertDialogTitle>템플릿 삭제</AlertDialogTitle>
                              <AlertDialogDescription>
                                정말로 "{template.name}" 템플릿을 삭제하시겠습니까?
                              </AlertDialogDescription>
                            </AlertDialogHeader>
                            <AlertDialogFooter>
                              <AlertDialogCancel>취소</AlertDialogCancel>
                              <AlertDialogAction onClick={() => handleDeleteTemplate(template.id)}>
                                삭제
                              </AlertDialogAction>
                            </AlertDialogFooter>
                          </AlertDialogContent>
                        </AlertDialog>
                      </div>
                    </CardContent>
                  </Card>
                ))}
              </div>
            )}
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}