"use client";

import React, { useState, useRef } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Upload, Download, FileText, AlertCircle, CheckCircle } from "lucide-react";
import { toast } from "sonner";
import { useTemplates } from "@/hooks/admin/useTemplates";

interface TemplateImportExportProps {
  onTemplateImported?: () => void;
}

interface ImportData {
  template_code: string;
  template_name: string;
  template_name_eng?: string;
  description?: string;
  category: string;
  icon_name?: string;
  default_size?: {
    width: number;
    height: number;
  };
  layout_config: any;
}

export function TemplateImportExport({ onTemplateImported }: TemplateImportExportProps) {
  const [isImportDialogOpen, setIsImportDialogOpen] = useState(false);
  const [importData, setImportData] = useState<ImportData | null>(null);
  const [importError, setImportError] = useState<string>("");
  const [jsonInput, setJsonInput] = useState("");
  const fileInputRef = useRef<HTMLInputElement>(null);

  const { importTemplate, isImporting } = useTemplates();

  // 파일 업로드 핸들러
  const handleFileUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;

    if (file.type !== "application/json") {
      setImportError("JSON 파일만 업로드할 수 있습니다.");
      return;
    }

    const reader = new FileReader();
    reader.onload = (e) => {
      try {
        const content = e.target?.result as string;
        const data = JSON.parse(content);
        validateAndSetImportData(data);
        setJsonInput(JSON.stringify(data, null, 2));
      } catch (error) {
        setImportError("유효하지 않은 JSON 파일입니다.");
      }
    };
    reader.readAsText(file);
  };

  // JSON 텍스트 입력 핸들러
  const handleJsonInputChange = (value: string) => {
    setJsonInput(value);
    if (!value.trim()) {
      setImportData(null);
      setImportError("");
      return;
    }

    try {
      const data = JSON.parse(value);
      validateAndSetImportData(data);
    } catch (error) {
      setImportError("유효하지 않은 JSON 형식입니다.");
      setImportData(null);
    }
  };

  // 가져오기 데이터 검증
  const validateAndSetImportData = (data: any) => {
    setImportError("");

    // 필수 필드 검증
    const requiredFields = ["template_code", "template_name", "category", "layout_config"];
    const missingFields = requiredFields.filter((field) => !data[field]);

    if (missingFields.length > 0) {
      setImportError(`필수 필드가 누락되었습니다: ${missingFields.join(", ")}`);
      setImportData(null);
      return;
    }

    // 템플릿 코드 형식 검증
    if (!/^[a-z0-9_-]+$/.test(data.template_code)) {
      setImportError("템플릿 코드는 영문 소문자, 숫자, 하이픈, 언더스코어만 사용할 수 있습니다.");
      setImportData(null);
      return;
    }

    // layout_config 구조 검증
    if (!data.layout_config.components || !Array.isArray(data.layout_config.components)) {
      setImportError("layout_config.components가 올바른 배열 형태가 아닙니다.");
      setImportData(null);
      return;
    }

    setImportData(data);
  };

  // 템플릿 가져오기 실행
  const handleImport = async () => {
    if (!importData) return;

    try {
      await importTemplate(importData);
      toast.success(`템플릿 '${importData.template_name}'이 성공적으로 가져왔습니다.`);
      setIsImportDialogOpen(false);
      setImportData(null);
      setJsonInput("");
      setImportError("");
      onTemplateImported?.();
    } catch (error: any) {
      toast.error(`템플릿 가져오기 실패: ${error.message}`);
    }
  };

  // 파일 선택 트리거
  const triggerFileSelect = () => {
    fileInputRef.current?.click();
  };

  return (
    <div className="flex space-x-2">
      {/* 가져오기 버튼 */}
      <Dialog open={isImportDialogOpen} onOpenChange={setIsImportDialogOpen}>
        <DialogTrigger asChild>
          <Button variant="outline">
            <Upload className="mr-2 h-4 w-4" />
            가져오기
          </Button>
        </DialogTrigger>
        <DialogContent className="max-w-4xl">
          <DialogHeader>
            <DialogTitle>템플릿 가져오기</DialogTitle>
          </DialogHeader>

          <div className="space-y-6">
            {/* 파일 업로드 영역 */}
            <Card>
              <CardHeader>
                <CardTitle className="text-lg">1. JSON 파일 업로드</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div
                  className="cursor-pointer rounded-lg border-2 border-dashed border-input p-8 text-center transition-colors hover:border-input"
                  onClick={triggerFileSelect}
                >
                  <Upload className="mx-auto mb-4 h-12 w-12 text-muted-foreground/70" />
                  <p className="mb-2 text-lg font-medium text-foreground">템플릿 JSON 파일을 선택하세요</p>
                  <p className="text-sm text-muted-foreground">또는 아래에 JSON 내용을 직접 입력하세요</p>
                </div>
                <input ref={fileInputRef} type="file" accept=".json" onChange={handleFileUpload} className="hidden" />
              </CardContent>
            </Card>

            {/* JSON 직접 입력 */}
            <Card>
              <CardHeader>
                <CardTitle className="text-lg">2. JSON 직접 입력</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <Textarea
                  placeholder="JSON 템플릿 데이터를 여기에 붙여넣으세요..."
                  value={jsonInput}
                  onChange={(e) => handleJsonInputChange(e.target.value)}
                  className="min-h-[200px] font-mono text-sm"
                />
              </CardContent>
            </Card>

            {/* 오류 메시지 */}
            {importError && (
              <Alert variant="destructive">
                <AlertCircle className="h-4 w-4" />
                <AlertDescription>{importError}</AlertDescription>
              </Alert>
            )}

            {/* 미리보기 */}
            {importData && (
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center text-lg">
                    <CheckCircle className="mr-2 h-5 w-5 text-emerald-600" />
                    3. 템플릿 미리보기
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <Label>템플릿 코드</Label>
                      <Input value={importData.template_code} readOnly />
                    </div>
                    <div>
                      <Label>템플릿명</Label>
                      <Input value={importData.template_name} readOnly />
                    </div>
                    <div>
                      <Label>카테고리</Label>
                      <Input value={importData.category} readOnly />
                    </div>
                    <div>
                      <Label>컴포넌트 개수</Label>
                      <Input value={`${importData.layout_config?.components?.length || 0}개`} readOnly />
                    </div>
                  </div>
                  {importData.description && (
                    <div>
                      <Label>설명</Label>
                      <Textarea value={importData.description} readOnly />
                    </div>
                  )}
                </CardContent>
              </Card>
            )}

            {/* 가져오기 버튼 */}
            <div className="flex justify-end space-x-2">
              <Button variant="outline" onClick={() => setIsImportDialogOpen(false)}>
                취소
              </Button>
              <Button onClick={handleImport} disabled={!importData || isImporting}>
                {isImporting ? "가져오는 중..." : "가져오기"}
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}

// 템플릿 가져오기/내보내기 샘플 데이터 생성 유틸리티
export const generateSampleTemplate = () => {
  return {
    template_code: "sample-form",
    template_name: "샘플 폼 템플릿",
    template_name_eng: "Sample Form Template",
    description: "기본적인 폼 입력 요소들을 포함한 샘플 템플릿",
    category: "form",
    icon_name: "form",
    default_size: {
      width: 400,
      height: 300,
    },
    layout_config: {
      components: [
        {
          type: "widget",
          widgetType: "text",
          label: "이름",
          position: { x: 0, y: 0 },
          size: { width: 200, height: 36 },
          style: {
            border: "1px solid #d1d5db",
            borderRadius: "4px",
            padding: "8px",
          },
        },
        {
          type: "widget",
          widgetType: "email",
          label: "이메일",
          position: { x: 0, y: 50 },
          size: { width: 200, height: 36 },
          style: {
            border: "1px solid #d1d5db",
            borderRadius: "4px",
            padding: "8px",
          },
        },
        {
          type: "widget",
          widgetType: "button",
          label: "저장",
          position: { x: 0, y: 100 },
          size: { width: 80, height: 36 },
          style: {
            backgroundColor: "#3b82f6",
            color: "#ffffff",
            border: "none",
            borderRadius: "6px",
          },
        },
      ],
    },
  };
};
