
"use client";

import { useState, useEffect } from "react";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Header } from "@/components/ui/header";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Trash2, Plus, Folder, HardDrive } from "lucide-react";

interface Library {
  id: number;
  path: string;
}

const SettingsPage = () => {
  const [libraries, setLibraries] = useState<Library[]>([]);
  const [newLibraryPath, setNewLibraryPath] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [scanStatus, setScanStatus] = useState<string>("");

  useEffect(() => {
    fetchLibraries();
  }, []);

  const fetchLibraries = async () => {
    try {
      const res = await fetch("/api/libraries");
      const data = await res.json();
      setLibraries(data);
    } catch (error) {
      console.error('Error fetching libraries:', error);
    }
  };

  const addLibrary = async () => {
    if (!newLibraryPath.trim()) {
      setError("Please enter a valid path");
      return;
    }

    try {
      const res = await fetch("/api/libraries", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ path: newLibraryPath.trim() }),
      });

      if (res.ok) {
        setNewLibraryPath("");
        setError(null);
        fetchLibraries();
      } else {
        const data = await res.json();
        setError(data.error || "Failed to add library");
      }
    } catch (error) {
      setError("Network error occurred");
    }
  };

  const deleteLibrary = async (id: number) => {
    if (!confirm("Are you sure you want to delete this library? This will not delete the actual files.")) {
      return;
    }

    try {
      const res = await fetch(`/api/libraries/${id}`, {
        method: "DELETE",
      });
      if (res.ok) {
        fetchLibraries();
      }
    } catch (error) {
      console.error('Error deleting library:', error);
    }
  };

  const [isScanning, setIsScanning] = useState(false);

  const scanLibraries = async () => {
    setIsScanning(true);
    setScanStatus("Scanning libraries...");
    
    try {
      const res = await fetch("/api/scan", {
        method: "POST",
      });
      
      if (res.ok) {
        setScanStatus("Scan completed successfully!");
        setTimeout(() => setScanStatus(""), 3000);
      } else {
        setScanStatus("Scan failed. Please try again.");
      }
    } catch (error) {
      setScanStatus("Network error during scan");
    } finally {
      setIsScanning(false);
    }
  };

  const getTotalStorage = () => {
    return libraries.reduce((total, lib) => {
      // Rough estimation based on path length
      return total + (lib.path.length * 100); // Placeholder calculation
    }, 0);
  };

  return (
    <div className="min-h-screen bg-zinc-950">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="mb-8">
          <h1 className="text-5xl font-bold text-white tracking-tight mb-2">
            Settings
          </h1>
          <p className="text-zinc-400 text-lg">
            Configure your media libraries and system preferences
          </p>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          <div className="lg:col-span-2 space-y-8">
            <div className="bg-zinc-900 rounded-xl border border-zinc-800 p-6">
              <div className="flex items-center gap-3 mb-6">
                <div className="w-10 h-10 bg-red-600 rounded-xl flex items-center justify-center shadow-lg shadow-red-600/20">
                  <Folder className="h-5 w-5 text-white" />
                </div>
                <div>
                  <h2 className="text-xl font-bold text-white">Media Libraries</h2>
                  <p className="text-sm text-zinc-400">Manage your media source directories</p>
                </div>
              </div>

              <div className="space-y-4">
                <div className="flex gap-3">
                  <input
                    type="text"
                    placeholder="/mnt/media or /path/to/media"
                    value={newLibraryPath}
                    onChange={(e) => {
                      setNewLibraryPath(e.target.value);
                      setError(null);
                    }}
                    onKeyPress={(e) => e.key === 'Enter' && addLibrary()}
                    className="flex-1 px-4 py-3 bg-zinc-800 border border-zinc-700 rounded-lg text-sm text-white focus:outline-none focus:ring-2 focus:ring-red-500 focus:border-transparent transition-all placeholder-zinc-500"
                  />
                  <button
                    onClick={addLibrary}
                    disabled={!newLibraryPath.trim()}
                    className="px-4 py-3 bg-red-600 text-white font-medium rounded-lg hover:bg-red-700 transition-all disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2 shadow-lg shadow-red-600/20"
                  >
                    <Plus size={16} />
                    Add
                  </button>
                </div>

                {error && (
                  <div className="p-3 bg-red-900/20 border border-red-800 rounded-lg">
                    <p className="text-sm text-red-400">{error}</p>
                  </div>
                )}

                {libraries.length > 0 && (
                  <div className="space-y-3">
                    <h3 className="text-sm font-semibold text-zinc-400 uppercase tracking-wider">
                      {libraries.length} {libraries.length === 1 ? 'Library' : 'Libraries'}
                    </h3>
                    <div className="space-y-2">
                      {libraries.map((lib) => (
                        <div key={lib.id} className="flex items-center justify-between p-4 bg-zinc-800 rounded-lg border border-zinc-700 group hover:border-zinc-600 transition-all">
                          <div className="flex items-center gap-3 flex-1 min-w-0">
                            <div className="w-8 h-8 bg-zinc-700 rounded-lg flex items-center justify-center">
                              <HardDrive className="h-4 w-4 text-zinc-300" />
                            </div>
                            <div className="min-w-0">
                              <p className="text-sm font-mono text-zinc-100 truncate">{lib.path}</p>
                              <p className="text-xs text-zinc-500">Ready to scan</p>
                            </div>
                          </div>
                          <button
                            onClick={() => deleteLibrary(lib.id)}
                            className="p-2 text-zinc-400 hover:text-red-500 hover:bg-red-900/20 rounded-lg transition-all"
                          >
                            <Trash2 size={16} />
                          </button>
                        </div>
                      ))}
                    </div>
                  </div>
                )}

                {libraries.length === 0 && (
                  <div className="text-center py-12">
                    <div className="w-16 h-16 bg-zinc-800 rounded-2xl flex items-center justify-center mx-auto mb-4">
                      <Folder className="h-8 w-8 text-zinc-500" />
                    </div>
                    <p className="text-zinc-400">No libraries configured</p>
                    <p className="text-sm text-zinc-500 mt-1">Add your first library to get started</p>
                  </div>
                )}
              </div>
            </div>

            <div className="bg-zinc-900 rounded-xl border border-zinc-800 p-6">
              <div className="flex items-center gap-3 mb-4">
                <div className="w-10 h-10 bg-green-600 rounded-xl flex items-center justify-center shadow-lg shadow-green-600/20">
                  <svg className="h-5 w-5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                  </svg>
                </div>
                <div>
                  <h2 className="text-xl font-bold text-white">Media Scanner</h2>
                  <p className="text-sm text-zinc-400">Discover new media files</p>
                </div>
              </div>

              <div className="space-y-4">
                <button
                  onClick={scanLibraries}
                  disabled={isScanning || libraries.length === 0}
                  className="w-full px-4 py-3 bg-gradient-to-r from-green-500 to-emerald-600 text-white font-medium rounded-xl hover:shadow-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
                >
                  {isScanning ? (
                    <>
                      <div className="animate-spin rounded-full h-4 w-4 border-2 border-white border-t-transparent"></div>
                      Scanning...
                    </>
                  ) : (
                    <>Scan Libraries</>
                  )}
                </button>

                {scanStatus && (
                  <div className={`p-3 rounded-lg ${scanStatus.includes('success') ? 'bg-green-900/20 border border-green-800' : 'bg-zinc-800 border border-zinc-700'}`}>
                    <p className={`text-sm ${scanStatus.includes('success') ? 'text-green-400' : 'text-zinc-400'}`}>
                      {scanStatus}
                    </p>
                  </div>
                )}

                <p className="text-sm text-zinc-500 text-center">
                  {libraries.length === 0 
                    ? "Add at least one library to enable scanning" 
                    : "Scan will discover new videos and photos"}
                </p>
              </div>
            </div>
          </div>

          <div className="space-y-6">
            <div className="bg-zinc-900 rounded-xl border border-zinc-800 p-6">
              <h3 className="text-lg font-bold text-white mb-4">System Status</h3>
              <div className="space-y-3">
                <div className="flex justify-between items-center p-3 bg-zinc-800 rounded-lg">
                  <span className="text-sm font-medium text-zinc-400">Libraries</span>
                  <span className="text-sm font-bold text-white">{libraries.length}</span>
                </div>
                <div className="flex justify-between items-center p-3 bg-zinc-800 rounded-lg">
                  <span className="text-sm font-medium text-zinc-400">Database</span>
                  <span className="text-sm font-bold text-white">SQLite</span>
                </div>
                <div className="flex justify-between items-center p-3 bg-zinc-800 rounded-lg">
                  <span className="text-sm font-medium text-zinc-400">Status</span>
                  <span className="text-sm font-bold text-green-400">Active</span>
                </div>
              </div>
            </div>

            <div className="bg-zinc-900 rounded-xl border border-zinc-800 p-6">
              <h3 className="text-lg font-bold text-white mb-4">Quick Actions</h3>
              <div className="space-y-2">
                <Link href="/videos" className="block w-full px-3 py-2 text-sm text-zinc-300 hover:bg-zinc-800 rounded-lg transition-colors">
                  View Videos
                </Link>
                <Link href="/photos" className="block w-full px-3 py-2 text-sm text-zinc-300 hover:bg-zinc-800 rounded-lg transition-colors">
                  View Photos
                </Link>
                <Link href="/folder-viewer" className="block w-full px-3 py-2 text-sm text-zinc-300 hover:bg-zinc-800 rounded-lg transition-colors">
                  Browse Files
                </Link>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default SettingsPage;
