import React, { useEffect, useState } from 'react';
import { base44 } from '@/api/base44Client';
import { useSettings } from '@/lib/SettingsContext';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Loader2, Upload, Save, CheckCircle2, Image as ImageIcon } from 'lucide-react';

const EMAIL_OPTIONS = [
  'info@solarconnectuk.com',
  'support@solarconnectuk.com',
  'appointments@solarconnectuk.com',
];

// Schema drives the form. `key` must match the backend's EDITABLE list.
const SECTIONS = [
  {
    title: 'Branding',
    fields: [
      { key: 'site_title', label: 'Site Title', type: 'text', help: 'Shown in the browser tab.' },
      { key: 'site_logo', label: 'Site Logo', type: 'image', help: 'Used in the navbar, footer, and enquiry page. Leave empty to use the default.' },
      { key: 'site_favicon', label: 'Site Favicon', type: 'image', help: 'Small icon in the browser tab. PNG, SVG, or ICO.' },
    ],
  },
  {
    title: 'Email Routing',
    fields: [
      { key: 'enquiry_notification_email', label: 'Enquiry Notifications', type: 'select', options: EMAIL_OPTIONS, help: 'New quote-form enquiries are sent to this address.' },
      { key: 'admin_default_recipient', label: 'Admin Email Tool Default', type: 'select', options: EMAIL_OPTIONS, help: 'Default recipient when emailing a lead from the admin panel.' },
    ],
  },
  {
    title: 'Social Links',
    fields: [
      { key: 'social_facebook', label: 'Facebook URL', type: 'text', help: 'Full link to your Facebook page.' },
      { key: 'social_instagram', label: 'Instagram URL', type: 'text', help: 'Full link to your Instagram profile.' },
      { key: 'social_linkedin', label: 'LinkedIn URL', type: 'text', help: 'Full link to your LinkedIn page. Leave empty to hide it from the site.' },
      { key: 'social_tiktok', label: 'TikTok URL', type: 'text', help: 'Full link to your TikTok profile. Leave empty to hide it from the site.' },
    ],
  },
  {
    title: 'Reviews',
    fields: [
      { key: 'reviews_require_approval', label: 'Reviews Require Approval', type: 'boolean', help: 'When on, new visitor reviews stay hidden until you approve them.' },
    ],
  },
];

export default function AdminSettings() {
  const { refreshSettings } = useSettings();
  const [values, setValues] = useState({});
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [saved, setSaved] = useState(false);
  const [error, setError] = useState('');
  const [uploading, setUploading] = useState(null); // key currently uploading

  useEffect(() => {
    (async () => {
      try {
        const rows = await base44.settings.list();
        const map = {};
        rows.forEach(r => { map[r.key] = r.value ?? ''; });
        setValues(map);
      } catch (err) {
        setError(err.message || 'Failed to load settings');
      } finally {
        setLoading(false);
      }
    })();
  }, []);

  const setValue = (key, value) => {
    setValues(prev => ({ ...prev, [key]: value }));
    setSaved(false);
  };

  const handleUpload = async (key, file) => {
    if (!file) return;
    setUploading(key);
    setError('');
    try {
      const { url } = await base44.settings.upload(file);
      setValue(key, url);
    } catch (err) {
      setError(err.message || 'Upload failed');
    } finally {
      setUploading(null);
    }
  };

  const handleSave = async () => {
    setSaving(true);
    setError('');
    try {
      await base44.settings.update(values);
      setSaved(true);
      refreshSettings(); // apply new branding immediately
    } catch (err) {
      setError(err.message || 'Failed to save settings');
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-24">
        <Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
      </div>
    );
  }

  return (
    <div>
      <span className="font-mono text-xs tracking-[0.3em] uppercase text-accent mb-3 block">// Configure</span>
      <h1 className="font-heading font-black text-2xl sm:text-3xl text-foreground mb-6 sm:mb-8">Settings</h1>

      {error && (
        <div className="mb-6 p-3 rounded-lg bg-destructive/10 border border-destructive/30 text-destructive text-sm">
          {error}
        </div>
      )}

      <div className="space-y-10">
        {SECTIONS.map(section => (
          <section key={section.title}>
            <h2 className="font-mono text-xs tracking-widest uppercase text-primary mb-4">{section.title}</h2>
            <div className="rounded-xl border border-border/40 bg-card/40 divide-y divide-border/30">
              {section.fields.map(field => (
                <div key={field.key} className="p-5 flex flex-col sm:flex-row sm:items-center gap-4">
                  <div className="sm:w-1/2">
                    <Label className="text-sm font-medium text-foreground">{field.label}</Label>
                    {field.help && (
                      <p className="text-xs text-muted-foreground mt-1">{field.help}</p>
                    )}
                  </div>
                  <div className="sm:w-1/2">
                    {field.type === 'text' && (
                      <Input
                        value={values[field.key] ?? ''}
                        onChange={e => setValue(field.key, e.target.value)}
                      />
                    )}

                    {field.type === 'boolean' && (
                      <Switch
                        checked={values[field.key] === '1' || values[field.key] === true}
                        onCheckedChange={v => setValue(field.key, v ? '1' : '0')}
                      />
                    )}

                    {field.type === 'select' && (
                      <Select
                        value={values[field.key] || ''}
                        onValueChange={v => setValue(field.key, v)}
                      >
                        <SelectTrigger>
                          <SelectValue placeholder="Choose…" />
                        </SelectTrigger>
                        <SelectContent>
                          {field.options.map(opt => (
                            <SelectItem key={opt} value={opt}>{opt}</SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    )}

                    {field.type === 'image' && (
                      <div className="flex items-center gap-4">
                        <div className="w-16 h-16 rounded-lg border border-border/50 bg-background/50 flex items-center justify-center overflow-hidden shrink-0">
                          {values[field.key] ? (
                            <img src={values[field.key]} alt={field.label} className="max-w-full max-h-full object-contain" />
                          ) : (
                            <ImageIcon className="w-6 h-6 text-muted-foreground/40" />
                          )}
                        </div>
                        <div className="space-y-2">
                          <label className="inline-flex items-center gap-2 px-3 py-2 rounded-lg border border-border/50 text-sm text-foreground cursor-pointer hover:border-primary/50 transition-colors">
                            {uploading === field.key
                              ? <Loader2 className="w-4 h-4 animate-spin" />
                              : <Upload className="w-4 h-4" />}
                            {uploading === field.key ? 'Uploading…' : 'Upload'}
                            <input
                              type="file"
                              accept="image/png,image/jpeg,image/webp,image/svg+xml,image/gif,image/x-icon,.ico"
                              className="hidden"
                              onChange={e => handleUpload(field.key, e.target.files?.[0])}
                            />
                          </label>
                          {values[field.key] && (
                            <button
                              onClick={() => setValue(field.key, '')}
                              className="block text-xs text-muted-foreground hover:text-destructive transition-colors"
                            >
                              Remove
                            </button>
                          )}
                        </div>
                      </div>
                    )}
                  </div>
                </div>
              ))}
            </div>
          </section>
        ))}
      </div>

      <div className="mt-8 flex items-center gap-4">
        <Button onClick={handleSave} disabled={saving} className="font-medium">
          {saving
            ? <><Loader2 className="w-4 h-4 mr-2 animate-spin" />Saving…</>
            : <><Save className="w-4 h-4 mr-2" />Save Settings</>}
        </Button>
        {saved && (
          <span className="inline-flex items-center gap-1.5 text-sm text-primary">
            <CheckCircle2 className="w-4 h-4" /> Saved
          </span>
        )}
      </div>
    </div>
  );
}
