"use client";

import { useCallback, useRef, useState } from "react";
import { Upload, FileDown } from "lucide-react";
import { Button } from "@/components/ui/button";

// ---------------------------------------------------------------------------
// Export helper  (non-component function)
// ---------------------------------------------------------------------------

/**
 * Generates a `.honeydue` file from the given data object and triggers a download.
 */
export function downloadHoneyDueFile(data: object, filename: string) {
  const json = JSON.stringify(data, null, 2);
  const blob = new Blob([json], { type: "application/json" });
  const url = URL.createObjectURL(blob);

  const anchor = document.createElement("a");
  anchor.href = url;
  anchor.download = filename.endsWith(".honeydue") ? filename : `${filename}.honeydue`;
  document.body.appendChild(anchor);
  anchor.click();

  // Cleanup
  document.body.removeChild(anchor);
  URL.revokeObjectURL(url);
}

// ---------------------------------------------------------------------------
// Import component
// ---------------------------------------------------------------------------

interface HoneyDueFileImportProps {
  onImport: (data: unknown) => void;
  accept?: string;
}

export function HoneyDueFileImport({ onImport, accept = ".honeydue" }: HoneyDueFileImportProps) {
  const inputRef = useRef<HTMLInputElement>(null);
  const [dragActive, setDragActive] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [fileName, setFileName] = useState<string | null>(null);

  const processFile = useCallback(
    (file: File) => {
      setError(null);
      setFileName(file.name);

      const reader = new FileReader();
      reader.onload = (e) => {
        try {
          const text = e.target?.result;
          if (typeof text !== "string") {
            setError("Failed to read file.");
            return;
          }
          const parsed = JSON.parse(text);
          onImport(parsed);
        } catch {
          setError("Invalid .honeydue file. Could not parse contents.");
          setFileName(null);
        }
      };
      reader.onerror = () => {
        setError("Failed to read file.");
        setFileName(null);
      };
      reader.readAsText(file);
    },
    [onImport],
  );

  function handleFileChange(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (file) processFile(file);
  }

  function handleDrop(e: React.DragEvent) {
    e.preventDefault();
    setDragActive(false);
    const file = e.dataTransfer.files[0];
    if (file) processFile(file);
  }

  function handleDragOver(e: React.DragEvent) {
    e.preventDefault();
    setDragActive(true);
  }

  function handleDragLeave(e: React.DragEvent) {
    e.preventDefault();
    setDragActive(false);
  }

  return (
    <div className="space-y-2">
      <div
        className={`flex flex-col items-center justify-center gap-3 rounded-lg border-2 border-dashed p-8 transition-colors cursor-pointer ${
          dragActive
            ? "border-primary bg-primary/5"
            : "border-muted-foreground/25 hover:border-muted-foreground/50"
        }`}
        onDrop={handleDrop}
        onDragOver={handleDragOver}
        onDragLeave={handleDragLeave}
        onClick={() => inputRef.current?.click()}
      >
        <Upload className="size-8 text-muted-foreground" />
        <div className="text-center">
          <p className="text-sm font-medium">
            Drop a .honeydue file here or click to browse
          </p>
          {fileName && (
            <p className="text-xs text-muted-foreground mt-1">
              Selected: {fileName}
            </p>
          )}
        </div>
        <input
          ref={inputRef}
          type="file"
          accept={accept}
          onChange={handleFileChange}
          className="hidden"
        />
      </div>
      {error && (
        <p className="text-sm text-destructive">{error}</p>
      )}
    </div>
  );
}

// ---------------------------------------------------------------------------
// Export button component  (convenience wrapper)
// ---------------------------------------------------------------------------

interface HoneyDueFileExportProps {
  data: object;
  filename: string;
  label?: string;
}

export function HoneyDueFileExport({ data, filename, label = "Export .honeydue" }: HoneyDueFileExportProps) {
  return (
    <Button
      variant="outline"
      size="sm"
      onClick={() => downloadHoneyDueFile(data, filename)}
    >
      <FileDown className="size-4 mr-2" />
      {label}
    </Button>
  );
}
