'use client';

import { useState, useRef, useCallback } from 'react';
import { clsx } from 'clsx';
import { Upload, FileText, Loader2, Sparkles, X, Tag } from 'lucide-react';
import { saveDocument } from '@/lib/api';
import { extractMetadata, isFeatureEnabled } from '@/lib/ai';
import { useToast } from './toast';

interface FileUploadZoneProps {
  vaultFullName: string;
  currentPath: string;
  onUploadComplete: () => void;
  label?: string;
}

interface ExtractedMeta {
  title: string;
  description: string;
  tags: string[];
  classification: 'skill' | 'knowledge';
  classification_confidence: 'high' | 'medium' | 'low';
  classification_reasoning: string;
  knowledge_subtype?: string;
}

interface PendingFile {
  file: File;
  content: string;
  meta: ExtractedMeta | null;
  editableTitle: string;
  editableDescription: string;
  editableTags: string;
  editableType: 'skill' | 'knowledge';
}

function buildFrontmatter(meta: { title: string; description: string; tags: string[]; type: string }): string {
  const tagList = meta.tags.map(t => t.trim()).filter(Boolean);
  return `---
title: "${meta.title}"
description: "${meta.description}"
tags: [${tagList.map(t => `"${t}"`).join(', ')}]
type: "${meta.type}"
---
`;
}

export function FileUploadZone({ vaultFullName, currentPath, onUploadComplete, label = 'Upload file' }: FileUploadZoneProps) {
  const [dragging, setDragging] = useState(false);
  const [uploading, setUploading] = useState(false);
  const [pendingFile, setPendingFile] = useState<PendingFile | null>(null);
  const [extracting, setExtracting] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const { showToast } = useToast();

  const basePath = currentPath || 'knowledge';

  const handleFiles = useCallback(async (files: FileList) => {
    if (files.length === 0) return;

    // Smart Upload: if AI enabled and single file, show review screen
    const smartUploadEnabled = isFeatureEnabled('smartUpload');

    if (smartUploadEnabled && files.length === 1) {
      const file = files[0];
      setExtracting(true);
      try {
        const content = await readFileAsText(file);
        const meta = await extractMetadata(content, file.name);
        setPendingFile({
          file,
          content,
          meta,
          editableTitle: meta?.title || file.name.replace(/\.\w+$/, ''),
          editableDescription: meta?.description || '',
          editableTags: meta?.tags?.join(', ') || '',
          editableType: meta?.classification || 'knowledge',
        });
      } catch {
        // Fallback: upload without metadata
        await uploadFileDirect(files);
      } finally {
        setExtracting(false);
      }
      return;
    }

    // No AI or multiple files: upload directly
    await uploadFileDirect(files);
  }, [vaultFullName, basePath, onUploadComplete]);

  const uploadFileDirect = useCallback(async (files: FileList) => {
    setUploading(true);
    let successCount = 0;
    let failCount = 0;

    for (let i = 0; i < files.length; i++) {
      const file = files[i];
      try {
        const content = await readFileAsText(file);
        const filePath = `${basePath}/${file.name}`;
        const result = await saveDocument(
          vaultFullName,
          filePath,
          content,
          `Upload ${file.name} via KnowHub`
        );
        if (result) {
          successCount++;
        } else {
          failCount++;
        }
      } catch {
        failCount++;
      }
    }

    setUploading(false);
    if (successCount > 0) {
      showToast(`Uploaded ${successCount} file${successCount > 1 ? 's' : ''} successfully`, 'success');
      onUploadComplete();
    }
    if (failCount > 0) {
      showToast(`Failed to upload ${failCount} file${failCount > 1 ? 's' : ''}`, 'error');
    }
  }, [vaultFullName, basePath, onUploadComplete, showToast]);

  const handleConfirmSmartUpload = useCallback(async () => {
    if (!pendingFile) return;
    setUploading(true);
    try {
      const tags = pendingFile.editableTags.split(',').map(t => t.trim()).filter(Boolean);
      const frontmatter = buildFrontmatter({
        title: pendingFile.editableTitle,
        description: pendingFile.editableDescription,
        tags,
        type: pendingFile.editableType,
      });
      const finalContent = frontmatter + pendingFile.content;
      const filePath = `${basePath}/${pendingFile.file.name}`;
      const result = await saveDocument(
        vaultFullName,
        filePath,
        finalContent,
        `Upload ${pendingFile.file.name} via KnowHub (AI-enriched)`
      );
      if (result) {
        showToast(`Uploaded ${pendingFile.file.name} with metadata`, 'success');
        setPendingFile(null);
        onUploadComplete();
      } else {
        showToast('Failed to upload file', 'error');
      }
    } catch {
      showToast('Failed to upload file', 'error');
    } finally {
      setUploading(false);
    }
  }, [pendingFile, vaultFullName, basePath, onUploadComplete, showToast]);

  const handleDragOver = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setDragging(true);
  }, []);

  const handleDragLeave = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setDragging(false);
  }, []);

  const handleDrop = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setDragging(false);
    if (e.dataTransfer.files.length > 0) {
      handleFiles(e.dataTransfer.files);
    }
  }, [handleFiles]);


  return (
    <div className="mb-4 space-y-3">
      {/* Drop zone */}
      <div
        onDragOver={handleDragOver}
        onDragLeave={handleDragLeave}
        onDrop={handleDrop}
        className={clsx(
          'border-2 border-dashed rounded-lg p-4 text-center transition-colors',
          dragging
            ? 'border-document bg-document/5'
            : 'border-border hover:border-border-light',
          (uploading || extracting) && 'opacity-60 pointer-events-none'
        )}
      >
        {uploading ? (
          <div className="flex items-center justify-center gap-2 py-2">
            <Loader2 size={16} className="text-document animate-spin" />
            <span className="text-sm text-text-secondary">Uploading...</span>
          </div>
        ) : extracting ? (
          <div className="flex items-center justify-center gap-2 py-2">
            <Sparkles size={16} className="text-accent animate-pulse" />
            <span className="text-sm text-text-secondary">Extracting metadata with AI...</span>
          </div>
        ) : (
          <div className="flex items-center justify-center gap-4 py-2">
            <div className="flex items-center gap-2 text-text-muted">
              <Upload size={16} />
              <span className="text-sm">Drop files here or</span>
            </div>
            <button
              onClick={() => fileInputRef.current?.click()}
              className="flex items-center gap-1.5 px-3 py-1.5 text-sm rounded-md border border-border text-text-secondary hover:text-text-primary hover:bg-surface-elevated transition-colors"
            >
              <FileText size={14} />
              {label}
            </button>
          </div>
        )}
        <input
          ref={fileInputRef}
          type="file"
          multiple
          className="hidden"
          onChange={(e) => {
            if (e.target.files) handleFiles(e.target.files);
            e.target.value = '';
          }}
        />
      </div>

      {/* AI Import Review */}
      {pendingFile && (
        <div className="rounded-lg border border-accent/30 bg-surface p-4 space-y-3">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <Sparkles size={14} className="text-accent" />
              <span className="text-sm font-medium text-text-primary">Import Review</span>
              {pendingFile.meta && (
                <span className={clsx(
                  'text-[10px] px-1.5 py-0.5 rounded-full font-medium',
                  pendingFile.meta.classification_confidence === 'high'
                    ? 'bg-success/10 text-success'
                    : pendingFile.meta.classification_confidence === 'medium'
                      ? 'bg-warning/10 text-warning'
                      : 'bg-surface-elevated text-text-muted'
                )}>
                  {pendingFile.meta.classification_confidence} confidence
                </span>
              )}
            </div>
            <button
              onClick={() => setPendingFile(null)}
              className="p-1 rounded-md text-text-muted hover:text-text-primary transition-colors"
            >
              <X size={14} />
            </button>
          </div>

          <p className="text-xs text-text-muted">
            File: {pendingFile.file.name}
          </p>

          <div>
            <label className="text-xs font-medium text-text-secondary uppercase tracking-wider mb-1.5 block">
              Title
            </label>
            <input
              type="text"
              value={pendingFile.editableTitle}
              onChange={(e) => setPendingFile({ ...pendingFile, editableTitle: e.target.value })}
              className="w-full px-3 py-2 rounded-md bg-surface-elevated border border-border text-sm text-text-primary placeholder:text-text-muted outline-none focus:border-accent transition-colors"
            />
          </div>

          <div>
            <label className="text-xs font-medium text-text-secondary uppercase tracking-wider mb-1.5 block">
              Description
            </label>
            <textarea
              value={pendingFile.editableDescription}
              onChange={(e) => setPendingFile({ ...pendingFile, editableDescription: e.target.value })}
              rows={2}
              className="w-full px-3 py-2 rounded-md bg-surface-elevated border border-border text-sm text-text-primary placeholder:text-text-muted resize-none outline-none focus:border-accent transition-colors"
            />
          </div>

          <div>
            <label className="text-xs font-medium text-text-secondary uppercase tracking-wider mb-1.5 block">
              Tags (comma separated)
            </label>
            <div className="flex items-center gap-2">
              <Tag size={14} className="text-text-muted shrink-0" />
              <input
                type="text"
                value={pendingFile.editableTags}
                onChange={(e) => setPendingFile({ ...pendingFile, editableTags: e.target.value })}
                placeholder="e.g. guide, onboarding, process"
                className="flex-1 px-3 py-2 rounded-md bg-surface-elevated border border-border text-sm text-text-primary placeholder:text-text-muted outline-none focus:border-accent transition-colors"
              />
            </div>
          </div>

          <div>
            <label className="text-xs font-medium text-text-secondary uppercase tracking-wider mb-1.5 block">
              Type
            </label>
            <div className="flex gap-2">
              {(['knowledge', 'skill'] as const).map((t) => (
                <button
                  key={t}
                  onClick={() => setPendingFile({ ...pendingFile, editableType: t })}
                  className={clsx(
                    'px-3 py-1.5 rounded-md text-sm font-medium transition-colors border',
                    pendingFile.editableType === t
                      ? 'bg-accent text-white border-accent'
                      : 'bg-surface-elevated text-text-secondary border-border hover:text-text-primary'
                  )}
                >
                  {t.charAt(0).toUpperCase() + t.slice(1)}
                </button>
              ))}
            </div>
          </div>

          {pendingFile.meta?.classification_reasoning && (
            <p className="text-xs text-text-muted italic">
              AI reasoning: {pendingFile.meta.classification_reasoning}
            </p>
          )}

          <div className="flex justify-end gap-2">
            <button
              onClick={() => setPendingFile(null)}
              className="px-3 py-1.5 text-sm rounded-md border border-border text-text-secondary hover:text-text-primary hover:bg-surface-elevated transition-colors"
            >
              Cancel
            </button>
            <button
              onClick={handleConfirmSmartUpload}
              disabled={uploading}
              className={clsx(
                'px-3 py-1.5 text-sm rounded-md font-medium transition-colors',
                uploading
                  ? 'bg-surface-elevated text-text-muted cursor-not-allowed'
                  : 'bg-accent text-white hover:bg-accent-hover'
              )}
            >
              {uploading ? 'Uploading...' : 'Confirm & Upload'}
            </button>
          </div>
        </div>
      )}

    </div>
  );
}

function readFileAsText(file: File): Promise<string> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => resolve(reader.result as string);
    reader.onerror = reject;
    reader.readAsText(file);
  });
}
