import { useState } from 'react';
import { useAppContext } from '../AppContext';
import { db } from '../database';
import { Download, Upload, Globe, Moon, Sun, Monitor } from 'lucide-react';

export function SettingsScreen() {
  const { language, setLanguage, themeMode, setThemeMode } = useAppContext();
  const [backupStatus, setBackupStatus] = useState('');

  const handleExport = async () => {
    try {
      const spottings = await db.spottings.toArray();
      const places = await db.customPlaces.toArray();
      
      const backup = {
        version: 1,
        timestamp: new Date().toISOString(),
        spottings,
        places
      };

      const blob = new Blob([JSON.stringify(backup, null, 2)], { type: 'application/json' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `birdspotter_backup_${new Date().toISOString().split('T')[0]}.json`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
      
      setBackupStatus('Export successful!');
      setTimeout(() => setBackupStatus(''), 3000);
    } catch (error) {
      console.error(error);
      setBackupStatus('Export failed.');
    }
  };

  const handleImport = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    try {
      const text = await file.text();
      const backup = JSON.parse(text);

      if (backup.spottings) {
        await db.spottings.clear();
        await db.spottings.bulkAdd(backup.spottings);
      }
      if (backup.places) {
        await db.customPlaces.clear();
        await db.customPlaces.bulkAdd(backup.places);
      }

      setBackupStatus('Import successful!');
      setTimeout(() => setBackupStatus(''), 3000);
    } catch (error) {
      console.error(error);
      setBackupStatus('Import failed. Invalid file format.');
    }
  };

  return (
    <div className="flex flex-col h-full bg-zinc-50 dark:bg-zinc-950 px-4 pt-6 pb-24 overflow-y-auto">
      <h1 className="text-2xl font-semibold text-zinc-900 dark:text-zinc-100 mb-6">Settings</h1>

      <div className="space-y-6">
        {/* Appearance */}
        <section>
          <h2 className="text-sm font-semibold text-zinc-500 uppercase tracking-wider mb-3">Appearance</h2>
          <div className="bg-white dark:bg-zinc-900 rounded-2xl shadow-sm border border-zinc-200 dark:border-zinc-800 overflow-hidden">
            <div className="flex items-center justify-between p-4 border-b border-zinc-100 dark:border-zinc-800">
              <div className="flex items-center text-zinc-900 dark:text-zinc-100">
                <Globe className="w-5 h-5 mr-3 text-zinc-400" />
                <span className="font-medium">Language</span>
              </div>
              <select
                value={language}
                onChange={(e) => setLanguage(e.target.value)}
                className="bg-zinc-50 dark:bg-zinc-950 border border-zinc-200 dark:border-zinc-800 rounded-lg px-3 py-1.5 text-sm outline-none dark:text-white"
              >
                <option value="en">English</option>
                <option value="fi">Suomi</option>
              </select>
            </div>
            
            <div className="flex items-center justify-between p-4">
              <div className="flex items-center text-zinc-900 dark:text-zinc-100">
                {themeMode === 'dark' ? <Moon className="w-5 h-5 mr-3 text-zinc-400" /> : 
                 themeMode === 'light' ? <Sun className="w-5 h-5 mr-3 text-zinc-400" /> : 
                 <Monitor className="w-5 h-5 mr-3 text-zinc-400" />}
                <span className="font-medium">Theme</span>
              </div>
              <select
                value={themeMode}
                onChange={(e) => setThemeMode(e.target.value)}
                className="bg-zinc-50 dark:bg-zinc-950 border border-zinc-200 dark:border-zinc-800 rounded-lg px-3 py-1.5 text-sm outline-none dark:text-white"
              >
                <option value="system">System</option>
                <option value="light">Light</option>
                <option value="dark">Dark</option>
              </select>
            </div>
          </div>
        </section>

        {/* Backup & Restore */}
        <section>
          <h2 className="text-sm font-semibold text-zinc-500 uppercase tracking-wider mb-3">Backup & Restore</h2>
          <div className="bg-white dark:bg-zinc-900 rounded-2xl shadow-sm border border-zinc-200 dark:border-zinc-800 overflow-hidden p-4 space-y-4">
            <p className="text-sm text-zinc-600 dark:text-zinc-400">
              Export your spottings and custom places to a JSON file, or restore from a previous backup.
            </p>
            
            <div className="flex space-x-3">
              <button
                onClick={handleExport}
                className="flex-1 flex items-center justify-center py-2.5 bg-zinc-100 dark:bg-zinc-800 hover:bg-zinc-200 dark:hover:bg-zinc-700 text-zinc-900 dark:text-zinc-100 rounded-xl font-medium transition-colors text-sm"
              >
                <Download className="w-4 h-4 mr-2" />
                Export
              </button>
              
              <label className="flex-1 flex items-center justify-center py-2.5 bg-zinc-100 dark:bg-zinc-800 hover:bg-zinc-200 dark:hover:bg-zinc-700 text-zinc-900 dark:text-zinc-100 rounded-xl font-medium transition-colors text-sm cursor-pointer">
                <Upload className="w-4 h-4 mr-2" />
                Import
                <input
                  type="file"
                  accept=".json"
                  onChange={handleImport}
                  className="hidden"
                />
              </label>
            </div>

            {backupStatus && (
              <p className="text-sm text-emerald-600 dark:text-emerald-400 text-center font-medium">
                {backupStatus}
              </p>
            )}
          </div>
        </section>

        {/* About */}
        <section>
          <div className="bg-white dark:bg-zinc-900 rounded-2xl shadow-sm border border-zinc-200 dark:border-zinc-800 p-4 text-center">
            <h3 className="font-semibold text-zinc-900 dark:text-zinc-100">BirdSpotter Web</h3>
            <p className="text-xs text-zinc-500 mt-1">
              A Progressive Web App version of the offline-first Flutter design.
              Uses IndexedDB for local storage and browser Geolocation.
            </p>
          </div>
        </section>
      </div>
    </div>
  );
}
