"use client";

import { useState, useRef } from "react";
import { Plus, FileText, Upload, FolderOpen } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger, DialogDescription, DialogFooter } from "@/components/ui/dialog";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
import type { CreateSkillRequest } from "@/lib/api/skills";

const SKILLMD_PLACEHOLDER = `---
name: my-skill
description: >
  이 스킬이 무엇을 하는지 설명합니다.
---

# My Skill

## 사용 방법

1. 스킬 사용법을 여기에 작성합니다.`;

type AddSkillDialogProps = {
  onAdd: (req: CreateSkillRequest) => Promise<void>;
  onUploadZip?: (file: File) => Promise<void>;
  onImportPath?: (path: string) => Promise<void>;
};

export function AddSkillDialog({ onAdd, onUploadZip, onImportPath }: AddSkillDialogProps) {
  const [open, setOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const [tab, setTab] = useState("form");

  // Form mode
  const [name, setName] = useState("");
  const [description, setDescription] = useState("");
  const [instructions, setInstructions] = useState("");

  // Import mode
  const [importText, setImportText] = useState("");
  const [importError, setImportError] = useState<string | null>(null);

  // Upload mode
  const [zipFile, setZipFile] = useState<File | null>(null);
  const [importPath, setImportPath] = useState("");
  const [uploadError, setUploadError] = useState<string | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const reset = () => {
    setName("");
    setDescription("");
    setInstructions("");
    setImportText("");
    setImportError(null);
    setZipFile(null);
    setImportPath("");
    setUploadError(null);
    setTab("form");
  };

  const handleFormSubmit = async () => {
    if (!name.trim() || !description.trim()) return;
    setLoading(true);
    try {
      await onAdd({ name: name.trim(), description: description.trim(), instructions: instructions.trim() || undefined });
      reset();
      setOpen(false);
    } catch (err) {
      console.error("Failed to create skill:", err);
    } finally {
      setLoading(false);
    }
  };

  const handleImportSubmit = async () => {
    setImportError(null);
    const text = importText.trim();
    if (!text) return;

    // Parse YAML frontmatter
    if (!text.startsWith("---")) {
      setImportError("SKILL.md는 --- 로 시작하는 YAML frontmatter가 필요합니다.");
      return;
    }

    const parts = text.split("---");
    if (parts.length < 3) {
      setImportError("YAML frontmatter 형식이 올바르지 않습니다. ---로 감싸진 YAML이 필요합니다.");
      return;
    }

    // Simple YAML parsing for name and description
    const yamlStr = parts[1];
    let parsedName = "";
    let parsedDesc = "";

    for (const line of yamlStr.split("\n")) {
      const trimmed = line.trim();
      if (trimmed.startsWith("name:")) {
        parsedName = trimmed.slice(5).trim();
      } else if (trimmed.startsWith("description:")) {
        const val = trimmed.slice(12).trim();
        if (val && val !== ">") {
          parsedDesc = val;
        }
      } else if (parsedDesc === "" && !trimmed.startsWith("-") && !trimmed.includes(":") && trimmed) {
        // Continuation of multi-line description
        parsedDesc = trimmed;
      }
    }

    if (!parsedName) {
      setImportError("frontmatter에서 name 필드를 찾을 수 없습니다.");
      return;
    }

    const body = parts.slice(2).join("---").trim();

    setLoading(true);
    try {
      await onAdd({
        name: parsedName,
        description: parsedDesc || parsedName,
        instructions: body,
      });
      reset();
      setOpen(false);
    } catch (err: unknown) {
      const message = err instanceof Error ? err.message : "스킬 생성에 실패했습니다.";
      setImportError(message);
    } finally {
      setLoading(false);
    }
  };

  const handleZipUpload = async () => {
    if (!zipFile || !onUploadZip) return;
    setUploadError(null);
    setLoading(true);
    try {
      await onUploadZip(zipFile);
      reset();
      setOpen(false);
    } catch (err: unknown) {
      const message = err instanceof Error ? err.message : "ZIP 업로드에 실패했습니다.";
      setUploadError(message);
    } finally {
      setLoading(false);
    }
  };

  const handlePathImport = async () => {
    if (!importPath.trim() || !onImportPath) return;
    setUploadError(null);
    setLoading(true);
    try {
      await onImportPath(importPath.trim());
      reset();
      setOpen(false);
    } catch (err: unknown) {
      const message = err instanceof Error ? err.message : "경로 임포트에 실패했습니다.";
      setUploadError(message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button className="h-12 rounded-none px-8 flex gap-3 bg-primary text-primary-foreground font-black uppercase tracking-widest shadow-[0_8px_20px_-5px_rgba(var(--primary),0.3)] hover:translate-y-[-1px] transition-all">
          <Plus className="w-5 h-5" />
          Add Skill
        </Button>
      </DialogTrigger>
      <DialogContent className="sm:max-w-[600px] bg-sidebar border-foreground/10 text-foreground p-0 overflow-hidden max-h-[90vh] overflow-y-auto">
        <div className="h-1.5 w-full bg-[repeating-linear-gradient(45deg,var(--primary),var(--primary)_10px,transparent_10px,transparent_20px)]" />
        <div className="p-8 space-y-6">
          <DialogHeader>
            <DialogTitle className="text-3xl font-black uppercase tracking-tighter text-foreground">Add Agent Skill</DialogTitle>
            <DialogDescription className="text-foreground/60 font-medium uppercase text-[10px] tracking-widest pt-2">
              Register a new agent skill to the Nexus Agent platform.
            </DialogDescription>
          </DialogHeader>

          <Tabs value={tab} onValueChange={setTab}>
            <TabsList className="w-full bg-foreground/5 border border-foreground/10 rounded-none h-11">
              <TabsTrigger value="form" className="flex-1 rounded-none text-[10px] font-black uppercase tracking-widest data-[state=active]:bg-primary/20 data-[state=active]:text-primary">
                Form
              </TabsTrigger>
              <TabsTrigger value="import" className="flex-1 rounded-none text-[10px] font-black uppercase tracking-widest data-[state=active]:bg-primary/20 data-[state=active]:text-primary">
                <FileText className="w-3.5 h-3.5 mr-1.5" />
                Import
              </TabsTrigger>
              <TabsTrigger value="upload" className="flex-1 rounded-none text-[10px] font-black uppercase tracking-widest data-[state=active]:bg-primary/20 data-[state=active]:text-primary">
                <Upload className="w-3.5 h-3.5 mr-1.5" />
                Upload
              </TabsTrigger>
            </TabsList>

            {/* Form Mode */}
            <TabsContent value="form" className="mt-6">
              <div className="grid gap-6">
                <div className="grid gap-3">
                  <Label className="text-[10px] font-black uppercase tracking-widest text-primary">Skill Name</Label>
                  <Input
                    placeholder="e.g. pdf-processing"
                    className="bg-black/20 border-foreground/10 h-11 text-sm font-mono"
                    value={name}
                    onChange={(e) => setName(e.target.value)}
                  />
                  <p className="text-[10px] text-foreground/30 font-mono">소문자, 숫자, 하이픈만 사용 가능</p>
                </div>

                <div className="grid gap-3">
                  <Label className="text-[10px] font-black uppercase tracking-widest text-primary">Description</Label>
                  <textarea
                    placeholder="스킬이 무엇을 하는지, 언제 사용해야 하는지 설명합니다."
                    className="bg-black/20 border border-foreground/10 rounded-md p-3 text-xs font-mono text-foreground min-h-[80px] resize-y"
                    value={description}
                    onChange={(e) => setDescription(e.target.value)}
                  />
                </div>

                <div className="grid gap-3">
                  <Label className="text-[10px] font-black uppercase tracking-widest text-primary">Instructions (Markdown)</Label>
                  <textarea
                    placeholder={"# My Skill\n\n## 사용 방법\n\n1. 스텝 1\n2. 스텝 2"}
                    className="bg-black/20 border border-foreground/10 rounded-md p-3 text-xs font-mono text-foreground min-h-[160px] resize-y"
                    value={instructions}
                    onChange={(e) => setInstructions(e.target.value)}
                  />
                </div>
              </div>

              <DialogFooter className="pt-6 border-t border-foreground/10 mt-6">
                <Button
                  onClick={handleFormSubmit}
                  disabled={loading || !name.trim() || !description.trim()}
                  className="w-full h-14 bg-primary text-primary-foreground font-black uppercase tracking-[0.2em] hover:opacity-90"
                >
                  {loading ? "Creating..." : "Create Skill"}
                </Button>
              </DialogFooter>
            </TabsContent>

            {/* Import Mode */}
            <TabsContent value="import" className="mt-6">
              <div className="grid gap-4">
                <div className="grid gap-3">
                  <Label className="text-[10px] font-black uppercase tracking-widest text-primary">
                    SKILL.md 내용 붙여넣기
                  </Label>
                  <p className="text-[10px] text-foreground/40 font-mono">
                    YAML frontmatter가 포함된 SKILL.md 전체 내용을 붙여넣기 하세요.
                  </p>
                  <textarea
                    placeholder={SKILLMD_PLACEHOLDER}
                    className="bg-black/30 border border-foreground/10 rounded-md p-4 text-xs font-mono text-foreground min-h-[280px] resize-y leading-relaxed focus:outline-none focus:border-primary/50 transition-colors"
                    value={importText}
                    onChange={(e) => {
                      setImportText(e.target.value);
                      setImportError(null);
                    }}
                    spellCheck={false}
                  />
                </div>

                {importError && (
                  <div className="p-3 rounded-md bg-red-500/10 border border-red-500/20 text-red-400 text-xs font-mono">
                    {importError}
                  </div>
                )}

                <div className="p-4 rounded-md bg-foreground/5 border border-foreground/5 space-y-2">
                  <p className="text-[9px] font-black uppercase tracking-widest text-foreground/30">필수 형식</p>
                  <div className="text-[10px] font-mono text-foreground/50 space-y-1">
                    <p>--- (YAML frontmatter: name, description 필수) ---</p>
                    <p>Markdown 본문 (지시사항)</p>
                  </div>
                </div>
              </div>

              <DialogFooter className="pt-6 border-t border-foreground/10 mt-6">
                <Button
                  onClick={handleImportSubmit}
                  disabled={loading || !importText.trim()}
                  className="w-full h-14 bg-primary text-primary-foreground font-black uppercase tracking-[0.2em] hover:opacity-90"
                >
                  <FileText className="w-4 h-4 mr-2" />
                  {loading ? "Importing..." : "Import & Create"}
                </Button>
              </DialogFooter>
            </TabsContent>
            {/* Upload Mode */}
            <TabsContent value="upload" className="mt-6">
              <div className="grid gap-6">
                {/* ZIP Upload */}
                <div className="grid gap-3">
                  <Label className="text-[10px] font-black uppercase tracking-widest text-primary">
                    ZIP 파일 업로드
                  </Label>
                  <p className="text-[10px] text-foreground/40 font-mono">
                    SKILL.md가 포함된 스킬 폴더를 ZIP으로 압축하여 업로드하세요.
                  </p>
                  <input
                    ref={fileInputRef}
                    type="file"
                    accept=".zip"
                    className="hidden"
                    onChange={(e) => {
                      setZipFile(e.target.files?.[0] || null);
                      setUploadError(null);
                    }}
                  />
                  <div
                    className="border-2 border-dashed border-foreground/10 rounded-md p-8 text-center cursor-pointer hover:border-primary/30 transition-colors"
                    onClick={() => fileInputRef.current?.click()}
                  >
                    {zipFile ? (
                      <div className="space-y-2">
                        <Upload className="w-8 h-8 text-primary mx-auto" />
                        <p className="text-sm font-mono text-foreground">{zipFile.name}</p>
                        <p className="text-[10px] text-foreground/40 font-mono">
                          {(zipFile.size / 1024).toFixed(1)} KB
                        </p>
                      </div>
                    ) : (
                      <div className="space-y-2">
                        <Upload className="w-8 h-8 text-foreground/20 mx-auto" />
                        <p className="text-xs text-foreground/40 font-mono">
                          클릭하여 .zip 파일 선택
                        </p>
                      </div>
                    )}
                  </div>
                  <Button
                    onClick={handleZipUpload}
                    disabled={loading || !zipFile}
                    className="w-full h-12 bg-primary text-primary-foreground font-black uppercase tracking-[0.2em] hover:opacity-90"
                  >
                    <Upload className="w-4 h-4 mr-2" />
                    {loading && tab === "upload" && zipFile ? "Uploading..." : "Upload ZIP"}
                  </Button>
                </div>

                <div className="relative">
                  <div className="absolute inset-0 flex items-center">
                    <div className="w-full border-t border-foreground/10" />
                  </div>
                  <div className="relative flex justify-center">
                    <span className="bg-sidebar px-4 text-[10px] font-black uppercase tracking-widest text-foreground/30">OR</span>
                  </div>
                </div>

                {/* Path Import */}
                <div className="grid gap-3">
                  <Label className="text-[10px] font-black uppercase tracking-widest text-primary">
                    로컬 경로에서 가져오기
                  </Label>
                  <p className="text-[10px] text-foreground/40 font-mono">
                    서버에 있는 스킬 폴더의 절대 경로를 입력하세요.
                  </p>
                  <div className="flex gap-2">
                    <Input
                      placeholder="/path/to/skill-folder"
                      className="bg-black/20 border-foreground/10 h-11 text-sm font-mono flex-1"
                      value={importPath}
                      onChange={(e) => {
                        setImportPath(e.target.value);
                        setUploadError(null);
                      }}
                    />
                    <Button
                      onClick={handlePathImport}
                      disabled={loading || !importPath.trim()}
                      className="h-11 px-6 bg-primary text-primary-foreground font-black uppercase tracking-widest hover:opacity-90"
                    >
                      <FolderOpen className="w-4 h-4 mr-2" />
                      {loading && tab === "upload" && importPath ? "Importing..." : "Import"}
                    </Button>
                  </div>
                </div>

                {uploadError && (
                  <div className="p-3 rounded-md bg-red-500/10 border border-red-500/20 text-red-400 text-xs font-mono">
                    {uploadError}
                  </div>
                )}

                <div className="p-4 rounded-md bg-foreground/5 border border-foreground/5 space-y-2">
                  <p className="text-[9px] font-black uppercase tracking-widest text-foreground/30">스킬 폴더 구조</p>
                  <div className="text-[10px] font-mono text-foreground/50 space-y-0.5">
                    <p>my-skill/</p>
                    <p className="pl-3">SKILL.md &nbsp;&nbsp;<span className="text-primary/60">(필수)</span></p>
                    <p className="pl-3">scripts/ &nbsp;&nbsp;<span className="text-foreground/30">(선택)</span></p>
                    <p className="pl-3">references/ &nbsp;&nbsp;<span className="text-foreground/30">(선택)</span></p>
                  </div>
                </div>
              </div>
            </TabsContent>
          </Tabs>
        </div>
      </DialogContent>
    </Dialog>
  );
}
