'use client';

import * as React from 'react';
import { X, Settings as SettingsIcon, RotateCcw } from 'lucide-react';
import { Button } from './Button';
import { Card } from './Card';
import { Select } from './Select';
import { getSettings, saveSettings, resetSettings, type UserSettings } from '@/lib/storage/settings';

interface SettingsModalProps {
  isOpen: boolean;
  onClose: () => void;
}

export function SettingsModal({ isOpen, onClose }: SettingsModalProps) {
  const [settings, setSettings] = React.useState<UserSettings>(getSettings());

  // Load settings when modal opens
  React.useEffect(() => {
    if (isOpen) {
      setSettings(getSettings());
    }
  }, [isOpen]);

  const handleSettingChange = (key: keyof UserSettings, value: any) => {
    const updated = { ...settings, [key]: value };
    setSettings(updated);
    saveSettings({ [key]: value });
  };

  const handleReset = () => {
    if (confirm('Are you sure you want to reset all settings to defaults?')) {
      resetSettings();
      setSettings(getSettings());
    }
  };

  if (!isOpen) return null;

  return (
    <>
      {/* Backdrop */}
      <div
        className="fixed inset-0 bg-black/50 z-40 animate-fadeIn"
        onClick={onClose}
      />

      {/* Modal */}
      <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
        <Card className="w-full max-w-md max-h-[80vh] overflow-y-auto animate-fadeIn">
          <div className="p-6">
            {/* Header */}
            <div className="flex items-center justify-between mb-6">
              <div className="flex items-center gap-2">
                <SettingsIcon className="h-5 w-5 text-primary" />
                <h2 className="text-lg font-semibold">Settings</h2>
              </div>
              <Button variant="ghost" size="icon" onClick={onClose}>
                <X className="h-4 w-4" />
              </Button>
            </div>

            {/* Settings */}
            <div className="space-y-6">
              {/* Quality Preferences */}
              <div>
                <h3 className="text-sm font-semibold mb-3">Quality Preferences</h3>
                <Select
                  label="Default Quality Preset"
                  value={settings.defaultQualityPreset}
                  onValueChange={(value) =>
                    handleSettingChange('defaultQualityPreset', value as UserSettings['defaultQualityPreset'])
                  }
                  options={[
                    { value: 'high-quality', label: 'High Quality' },
                    { value: 'balanced', label: 'Balanced' },
                    { value: 'small-file', label: 'Small File' },
                    { value: 'web-optimized', label: 'Web Optimized' },
                  ]}
                />
              </div>

              {/* Behavior Preferences */}
              <div>
                <h3 className="text-sm font-semibold mb-3">Behavior</h3>
                <div className="space-y-3">
                  <label className="flex items-center gap-2 cursor-pointer">
                    <input
                      type="checkbox"
                      checked={settings.autoStartConversion}
                      onChange={(e) => handleSettingChange('autoStartConversion', e.target.checked)}
                      className="w-4 h-4 rounded border-border text-primary focus:ring-2 focus:ring-primary"
                    />
                    <span className="text-sm">Auto-start conversion when files are selected</span>
                  </label>

                  <label className="flex items-center gap-2 cursor-pointer">
                    <input
                      type="checkbox"
                      checked={settings.showConversionHistory}
                      onChange={(e) => handleSettingChange('showConversionHistory', e.target.checked)}
                      className="w-4 h-4 rounded border-border text-primary focus:ring-2 focus:ring-primary"
                    />
                    <span className="text-sm">Show conversion history</span>
                  </label>

                  <label className="flex items-center gap-2 cursor-pointer">
                    <input
                      type="checkbox"
                      checked={settings.clearHistoryOnReset}
                      onChange={(e) => handleSettingChange('clearHistoryOnReset', e.target.checked)}
                      className="w-4 h-4 rounded border-border text-primary focus:ring-2 focus:ring-primary"
                    />
                    <span className="text-sm">Clear history when resetting converter</span>
                  </label>
                </div>
              </div>

              {/* Default Formats */}
              <div>
                <h3 className="text-sm font-semibold mb-3">Default Output Formats</h3>
                <div className="space-y-3">
                  <Select
                    label="Video"
                    value={settings.defaultVideoFormat || 'none'}
                    onValueChange={(value) =>
                      handleSettingChange('defaultVideoFormat', value === 'none' ? undefined : value)
                    }
                    options={[
                      { value: 'none', label: 'No default' },
                      { value: 'mp4', label: 'MP4' },
                      { value: 'webm', label: 'WebM' },
                      { value: 'avi', label: 'AVI' },
                      { value: 'mov', label: 'MOV' },
                    ]}
                  />

                  <Select
                    label="Audio"
                    value={settings.defaultAudioFormat || 'none'}
                    onValueChange={(value) =>
                      handleSettingChange('defaultAudioFormat', value === 'none' ? undefined : value)
                    }
                    options={[
                      { value: 'none', label: 'No default' },
                      { value: 'mp3', label: 'MP3' },
                      { value: 'wav', label: 'WAV' },
                      { value: 'ogg', label: 'OGG' },
                      { value: 'aac', label: 'AAC' },
                    ]}
                  />

                  <Select
                    label="Image"
                    value={settings.defaultImageFormat || 'none'}
                    onValueChange={(value) =>
                      handleSettingChange('defaultImageFormat', value === 'none' ? undefined : value)
                    }
                    options={[
                      { value: 'none', label: 'No default' },
                      { value: 'webp', label: 'WebP' },
                      { value: 'png', label: 'PNG' },
                      { value: 'jpg', label: 'JPG' },
                      { value: 'gif', label: 'GIF' },
                    ]}
                  />
                </div>
              </div>
            </div>

            {/* Footer */}
            <div className="mt-6 flex gap-3">
              <Button onClick={handleReset} variant="outline" className="flex-1 gap-2">
                <RotateCcw className="h-4 w-4" />
                Reset to Defaults
              </Button>
              <Button onClick={onClose} className="flex-1">
                Done
              </Button>
            </div>
          </div>
        </Card>
      </div>
    </>
  );
}
