'use client';

import { useState, useCallback } from 'react';
import { Zap, Trash2, Loader2, FileText, ArrowLeft, Folder } from 'lucide-react';
import type { Skill } from '@/lib/types';
import { deleteFile } from '@/lib/api';
import { ConfirmationModal } from './confirmation-modal';
import { MarkdownViewer } from './markdown-viewer';
import { CommitHistory } from './commit-history';
import { useToast } from './toast';

function stripFrontmatter(content: string): string {
  const match = content.match(/^---\n[\s\S]*?\n---\n?([\s\S]*)$/);
  return match ? match[1].trim() : content;
}

interface SkillDetailProps {
  skill: Skill;
  vaultFullName: string;
  onDelete?: () => void;
  onMutate?: () => void;
}

export function SkillDetail({ skill, vaultFullName, onDelete, onMutate }: SkillDetailProps) {
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [deleting, setDeleting] = useState(false);
  // File viewer state: null = show SKILL.md, string = show that file
  const [viewingFile, setViewingFile] = useState<string | null>(null);
  const [fileContent, setFileContent] = useState<string | null>(null);
  const [loadingFile, setLoadingFile] = useState(false);
  const { showToast } = useToast();

  const handleDelete = useCallback(async () => {
    setDeleting(true);
    try {
      const success = await deleteFile(skill.vaultFullName, skill.path);
      if (success) {
        showToast('Skill deleted', 'success');
        setShowDeleteConfirm(false);
        onDelete?.();
        onMutate?.();
      } else {
        showToast('Failed to delete skill', 'error');
      }
    } catch {
      showToast('Failed to delete skill', 'error');
    } finally {
      setDeleting(false);
    }
  }, [skill.vaultFullName, skill.path, showToast, onDelete, onMutate]);

  const handleViewFile = useCallback(async (filePath: string) => {
    setLoadingFile(true);
    setViewingFile(filePath);
    setFileContent(null);
    try {
      const { owner, repo } = (() => {
        const parts = vaultFullName.split('/');
        return { owner: parts[0], repo: parts.slice(1).join('/') };
      })();
      const auth = JSON.parse(localStorage.getItem('knowhub_auth') || '{}');
      const res = await fetch(`/api/proxy/repos/${owner}/${repo}/contents/${filePath}`, {
        headers: {
          'X-KnowHub-Server': auth.serverUrl || '',
          'X-KnowHub-Token': auth.token || '',
        },
      });
      if (res.ok) {
        const data = await res.json();
        if (data?.content) {
          const decoded = typeof atob !== 'undefined'
            ? atob(data.content.replace(/\n/g, ''))
            : Buffer.from(data.content, 'base64').toString('utf-8');
          setFileContent(decoded);
        } else {
          setFileContent('(Could not decode file content)');
        }
      } else {
        setFileContent('(Failed to load file)');
      }
    } catch {
      setFileContent('(Failed to load file)');
    } finally {
      setLoadingFile(false);
    }
  }, [vaultFullName]);

  const fileName = viewingFile ? viewingFile.split('/').pop() || '' : '';
  const isMarkdown = fileName.endsWith('.md');

  return (
    <>
      <div className="flex flex-col h-full overflow-y-auto">
        {/* Skill Content Card */}
        <div className="rounded-xl border border-white/5 bg-[#1c2026] p-5">
          {/* Header: name + delete */}
          <div className="flex items-start justify-between mb-4">
            <div className="flex items-center gap-3 min-w-0">
              <div className="flex items-center justify-center w-9 h-9 rounded-lg bg-[#67df70]/10 shrink-0">
                <Zap size={16} className="text-[#67df70]" />
              </div>
              <div className="min-w-0">
                <h2 className="text-base font-bold text-white truncate">{skill.name}</h2>
                <p className="text-xs text-gray-400 mt-0.5">{skill.description}</p>
              </div>
            </div>
            <div className="flex items-center gap-1.5 shrink-0 ml-3">
              <CommitHistory vaultFullName={vaultFullName} path={skill.path} diffFilePath={skill.entryPath} />
              <button
                onClick={() => setShowDeleteConfirm(true)}
                className="flex items-center gap-1.5 px-2.5 py-1.5 text-xs rounded-lg border border-white/10 text-red-400 hover:text-red-300 hover:bg-red-500/10 transition-colors"
              >
                <Trash2 size={12} />
                Delete
              </button>
            </div>
          </div>

          {/* Category badge */}
          <div className="mb-4">
            <span className="inline-block text-[10px] font-mono uppercase tracking-wider text-[#58a6ff] bg-[#58a6ff]/10 px-2 py-0.5 rounded">
              {skill.category}
            </span>
          </div>

          {/* File viewing: either SKILL.md or a selected file */}
          {viewingFile ? (
            <div>
              <button
                onClick={() => { setViewingFile(null); setFileContent(null); }}
                className="flex items-center gap-1.5 text-xs text-[#58a6ff] hover:text-white mb-3 transition-colors"
              >
                <ArrowLeft size={12} />
                Back to SKILL.md
              </button>
              <div className="text-xs font-mono text-gray-400 mb-2">{viewingFile.replace(skill.path + '/', '')}</div>
              {loadingFile ? (
                <div className="flex items-center gap-2 py-8 justify-center text-gray-500 text-sm">
                  <Loader2 size={14} className="animate-spin" />
                  Loading...
                </div>
              ) : fileContent !== null ? (
                isMarkdown ? (
                  <MarkdownViewer content={stripFrontmatter(fileContent)} />
                ) : (
                  <pre className="text-sm text-gray-300 font-mono whitespace-pre-wrap bg-[#10141a] rounded-lg p-4 border border-white/5 overflow-x-auto">
                    {fileContent}
                  </pre>
                )
              ) : null}
            </div>
          ) : (
            <MarkdownViewer content={stripFrontmatter(skill.content)} />
          )}

          {/* File tree */}
          {skill.files.length > 0 && (
            <div className="mt-5 pt-4 border-t border-white/5">
              <h3 className="text-xs font-mono uppercase tracking-wider text-gray-400 mb-3">
                Files ({skill.files.length + 1})
              </h3>
              <div className="rounded-lg border border-white/5 bg-[#10141a] p-3 font-mono text-sm">
                {/* Entry point */}
                <button
                  onClick={() => { setViewingFile(null); setFileContent(null); }}
                  className={`flex items-center gap-2 w-full text-left rounded px-1 py-0.5 transition-colors ${!viewingFile ? 'text-[#67df70]' : 'text-white hover:text-[#67df70]'}`}
                >
                  <FileText size={13} className="shrink-0" />
                  <span className="font-medium">SKILL.md</span>
                </button>
                {/* Group files by directory */}
                {(() => {
                  const groups: Record<string, string[]> = {};
                  for (const f of skill.files) {
                    const parts = f.replace(skill.path + '/', '').split('/');
                    const dir = parts.length > 1 ? parts[0] : '';
                    const file = parts[parts.length - 1];
                    if (!groups[dir]) groups[dir] = [];
                    groups[dir].push(file);
                  }
                  const dirs = Object.keys(groups).filter(d => d);
                  const rootFiles = groups[''] || [];

                  // Build a map from display name back to full path
                  const filePathMap: Record<string, string> = {};
                  for (const f of skill.files) {
                    const display = f.split('/').pop() || f;
                    filePathMap[display] = f;
                  }

                  return (
                    <>
                      {rootFiles.map((file) => (
                        <button
                          key={file}
                          onClick={() => handleViewFile(filePathMap[file] || file)}
                          className={`flex items-center gap-2 w-full text-left ml-0 mt-1 rounded px-1 py-0.5 transition-colors ${
                            viewingFile === (filePathMap[file] || file) ? 'text-[#67df70]' : 'text-gray-400 hover:text-white'
                          }`}
                        >
                          <span className="text-gray-600">├─</span>
                          <FileText size={13} className="shrink-0" />
                          <span>{file}</span>
                        </button>
                      ))}
                      {dirs.map((dir, di) => {
                        const files = groups[dir];
                        const isLast = di === dirs.length - 1 && rootFiles.length === 0;
                        return (
                          <div key={dir} className="mt-1">
                            <div className="flex items-center gap-2 text-gray-300">
                              <span className="text-gray-600">{isLast ? '└─' : '├─'}</span>
                              <Folder size={13} className="text-[#58a6ff] shrink-0" />
                              <span className="text-[#58a6ff]">{dir}/</span>
                            </div>
                            {files.map((file, fi) => (
                              <button
                                key={file}
                                onClick={() => handleViewFile(filePathMap[file] || `${skill.path}/${dir}/${file}`)}
                                className={`flex items-center gap-2 w-full text-left ml-5 mt-0.5 rounded px-1 py-0.5 transition-colors ${
                                  viewingFile?.endsWith(file) ? 'text-[#67df70]' : 'text-gray-400 hover:text-white'
                                }`}
                              >
                                <span className="text-gray-600">{fi === files.length - 1 ? '└─' : '├─'}</span>
                                <FileText size={12} className="shrink-0" />
                                <span>{file}</span>
                              </button>
                            ))}
                          </div>
                        );
                      })}
                    </>
                  );
                })()}
              </div>
            </div>
          )}

        </div>
      </div>

      <ConfirmationModal
        open={showDeleteConfirm}
        title="Delete Skill"
        description={`Are you sure you want to delete "${skill.name}"? This cannot be undone.`}
        confirmLabel={deleting ? 'Deleting...' : 'Delete'}
        onConfirm={handleDelete}
        onCancel={() => setShowDeleteConfirm(false)}
      />
    </>
  );
}
