"use client";

import { useState, useRef } from "react";
import { Plus, Upload, FolderOpen, Globe, FolderPlus, Archive } 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 } from "@/components/ui/dialog";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";

type AddPageDialogProps = {
  currentFolderId: string | null;
  onUpload: (file: File, name: string, description: string, parentId?: string) => Promise<void>;
  onUploadBundle: (files: File[], name: string, description: string, parentId?: string) => Promise<void>;
  onImportPath: (path: string, name: string, description: string, parentId?: string) => Promise<void>;
  onCreateBookmark: (name: string, url: string, description: string, parentId?: string) => Promise<void>;
  onCreateFolder: (name: string, description: string, parentId?: string) => Promise<void>;
};

export function AddPageDialog({ currentFolderId, onUpload, onUploadBundle, onImportPath, onCreateBookmark, onCreateFolder }: AddPageDialogProps) {
  const [open, setOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const [tab, setTab] = useState("upload");
  const [error, setError] = useState<string | null>(null);

  // Common
  const [name, setName] = useState("");
  const [description, setDescription] = useState("");

  // Upload mode
  const [htmlFile, setHtmlFile] = useState<File | null>(null);
  const [bundleFiles, setBundleFiles] = useState<File[] | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  // Path mode
  const [importPath, setImportPath] = useState("");

  // Bookmark mode
  const [bookmarkUrl, setBookmarkUrl] = useState("");

  const reset = () => {
    setName("");
    setDescription("");
    setHtmlFile(null);
    setBundleFiles(null);
    setImportPath("");
    setBookmarkUrl("");
    setError(null);
    setTab("upload");
  };

  const parentId = currentFolderId || undefined;

  const handleUpload = async () => {
    if (!name.trim()) return;
    setError(null);
    setLoading(true);
    try {
      if (bundleFiles && bundleFiles.length > 0) {
        await onUploadBundle(bundleFiles, name.trim(), description.trim(), parentId);
      } else if (htmlFile) {
        await onUpload(htmlFile, name.trim(), description.trim(), parentId);
      } else {
        return;
      }
      reset();
      setOpen(false);
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : "Upload failed.");
    } finally {
      setLoading(false);
    }
  };

  const handleImport = async () => {
    if (!importPath.trim() || !name.trim()) return;
    setError(null);
    setLoading(true);
    try {
      await onImportPath(importPath.trim(), name.trim(), description.trim(), parentId);
      reset();
      setOpen(false);
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : "Import failed.");
    } finally {
      setLoading(false);
    }
  };

  const handleBookmark = async () => {
    if (!bookmarkUrl.trim() || !name.trim()) return;
    setError(null);
    setLoading(true);
    try {
      await onCreateBookmark(name.trim(), bookmarkUrl.trim(), description.trim(), parentId);
      reset();
      setOpen(false);
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : "Bookmark creation failed.");
    } finally {
      setLoading(false);
    }
  };

  const handleFolder = async () => {
    if (!name.trim()) return;
    setError(null);
    setLoading(true);
    try {
      await onCreateFolder(name.trim(), description.trim(), parentId);
      reset();
      setOpen(false);
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : "Folder creation failed.");
    } 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 Page
        </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 Page</DialogTitle>
            <DialogDescription className="text-foreground/60 font-medium uppercase text-[10px] tracking-widest pt-2">
              HTML page, URL bookmark, or folder
            </DialogDescription>
          </DialogHeader>

          {/* Common fields */}
          <div className="grid gap-4">
            <div className="grid gap-3">
              <Label className="text-[10px] font-black uppercase tracking-widest text-primary">Name</Label>
              <Input
                placeholder="Page or folder name"
                className="bg-black/20 border-foreground/10 h-11 text-sm"
                value={name}
                onChange={(e) => setName(e.target.value)}
              />
            </div>
            <div className="grid gap-3">
              <Label className="text-[10px] font-black uppercase tracking-widest text-primary">Description (Optional)</Label>
              <Input
                placeholder="Brief description"
                className="bg-black/20 border-foreground/10 h-11 text-sm"
                value={description}
                onChange={(e) => setDescription(e.target.value)}
              />
            </div>
          </div>

          <Tabs value={tab} onValueChange={setTab}>
            <TabsList className="w-full bg-foreground/5 border border-foreground/10 rounded-none h-11">
              <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>
              <TabsTrigger value="path" className="flex-1 rounded-none text-[10px] font-black uppercase tracking-widest data-[state=active]:bg-primary/20 data-[state=active]:text-primary">
                <FolderOpen className="w-3.5 h-3.5 mr-1.5" />
                Path
              </TabsTrigger>
              <TabsTrigger value="bookmark" className="flex-1 rounded-none text-[10px] font-black uppercase tracking-widest data-[state=active]:bg-primary/20 data-[state=active]:text-primary">
                <Globe className="w-3.5 h-3.5 mr-1.5" />
                URL
              </TabsTrigger>
              <TabsTrigger value="folder" className="flex-1 rounded-none text-[10px] font-black uppercase tracking-widest data-[state=active]:bg-primary/20 data-[state=active]:text-primary">
                <FolderPlus className="w-3.5 h-3.5 mr-1.5" />
                Folder
              </TabsTrigger>
            </TabsList>

            {/* Upload Mode */}
            <TabsContent value="upload" className="mt-6">
              <div className="grid gap-4">
                <input
                  ref={fileInputRef}
                  type="file"
                  accept=".html,.htm,.zip,.js,.mjs,.css,.json,.svg,.png,.jpg,.jpeg,.gif,.webp,.ico,.woff,.woff2,.ttf,.eot,.map,.ts,.tsx,.jsx,.xml,.txt,.md,.csv"
                  multiple
                  className="hidden"
                  onChange={(e) => {
                    const fileList = e.target.files;
                    if (!fileList || fileList.length === 0) return;
                    setError(null);

                    const arr = Array.from(fileList);
                    const isZip = arr.length === 1 && arr[0].name.toLowerCase().endsWith(".zip");
                    const isMulti = arr.length > 1;

                    if (isZip || isMulti) {
                      setBundleFiles(arr);
                      setHtmlFile(null);
                      if (!name.trim()) {
                        const baseName = isZip
                          ? arr[0].name.replace(/\.zip$/i, "")
                          : "Bundle";
                        setName(baseName);
                      }
                    } else {
                      setHtmlFile(arr[0]);
                      setBundleFiles(null);
                      if (!name.trim()) {
                        setName(arr[0].name.replace(/\.(html|htm)$/i, ""));
                      }
                    }
                  }}
                />
                <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()}
                >
                  {bundleFiles ? (
                    <div className="space-y-2">
                      <Archive className="w-8 h-8 text-emerald-400 mx-auto" />
                      <p className="text-sm font-mono text-foreground">
                        {bundleFiles.length === 1 ? bundleFiles[0].name : `${bundleFiles.length} files selected`}
                      </p>
                      <p className="text-[10px] text-foreground/40 font-mono">
                        {(bundleFiles.reduce((s, f) => s + f.size, 0) / 1024).toFixed(1)} KB total
                      </p>
                    </div>
                  ) : htmlFile ? (
                    <div className="space-y-2">
                      <Upload className="w-8 h-8 text-primary mx-auto" />
                      <p className="text-sm font-mono text-foreground">{htmlFile.name}</p>
                      <p className="text-[10px] text-foreground/40 font-mono">
                        {(htmlFile.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">
                        Click to select .html, .zip, or multiple files
                      </p>
                    </div>
                  )}
                </div>

                <Button
                  onClick={handleUpload}
                  disabled={loading || (!htmlFile && !bundleFiles) || !name.trim()}
                  className="w-full h-14 bg-primary text-primary-foreground font-black uppercase tracking-[0.2em] hover:opacity-90"
                >
                  {bundleFiles ? <Archive className="w-4 h-4 mr-2" /> : <Upload className="w-4 h-4 mr-2" />}
                  {loading ? "Uploading..." : bundleFiles ? "Upload Bundle" : "Upload & Register"}
                </Button>
              </div>
            </TabsContent>

            {/* Path Mode */}
            <TabsContent value="path" className="mt-6">
              <div className="grid gap-4">
                <div className="grid gap-3">
                  <Label className="text-[10px] font-black uppercase tracking-widest text-primary">
                    Local File Path
                  </Label>
                  <Input
                    placeholder="e.g. /Users/user/docs/report.html"
                    className="bg-black/20 border-foreground/10 h-11 text-sm font-mono"
                    value={importPath}
                    onChange={(e) => {
                      setImportPath(e.target.value);
                      setError(null);
                    }}
                  />
                  <p className="text-[10px] text-foreground/30 font-mono">
                    Absolute path to an HTML file on the server machine.
                  </p>
                </div>

                <Button
                  onClick={handleImport}
                  disabled={loading || !importPath.trim() || !name.trim()}
                  className="w-full h-14 bg-primary text-primary-foreground font-black uppercase tracking-[0.2em] hover:opacity-90"
                >
                  <FolderOpen className="w-4 h-4 mr-2" />
                  {loading ? "Importing..." : "Import & Register"}
                </Button>
              </div>
            </TabsContent>

            {/* Bookmark Mode */}
            <TabsContent value="bookmark" className="mt-6">
              <div className="grid gap-4">
                <div className="grid gap-3">
                  <Label className="text-[10px] font-black uppercase tracking-widest text-primary">
                    URL
                  </Label>
                  <Input
                    placeholder="https://example.com/article"
                    className="bg-black/20 border-foreground/10 h-11 text-sm font-mono"
                    value={bookmarkUrl}
                    onChange={(e) => {
                      setBookmarkUrl(e.target.value);
                      setError(null);
                    }}
                  />
                </div>

                <Button
                  onClick={handleBookmark}
                  disabled={loading || !bookmarkUrl.trim() || !name.trim()}
                  className="w-full h-14 bg-primary text-primary-foreground font-black uppercase tracking-[0.2em] hover:opacity-90"
                >
                  <Globe className="w-4 h-4 mr-2" />
                  {loading ? "Creating..." : "Add Bookmark"}
                </Button>
              </div>
            </TabsContent>

            {/* Folder Mode */}
            <TabsContent value="folder" className="mt-6">
              <div className="grid gap-4">
                <p className="text-xs text-foreground/50 font-mono">
                  Create a folder to organize pages. Folders can be nested.
                </p>

                <Button
                  onClick={handleFolder}
                  disabled={loading || !name.trim()}
                  className="w-full h-14 bg-primary text-primary-foreground font-black uppercase tracking-[0.2em] hover:opacity-90"
                >
                  <FolderPlus className="w-4 h-4 mr-2" />
                  {loading ? "Creating..." : "Create Folder"}
                </Button>
              </div>
            </TabsContent>
          </Tabs>

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