
import React, { useState, useRef } from 'react';
import { Screen, CompanyProfile, UserProfile } from '../types';
import { Language, translations } from '../i18n';

interface AdminSettingsProps {
  navigateTo: (screen: Screen) => void;
  language: Language;
  user: UserProfile | null;
  companyProfile: CompanyProfile;
  setCompanyProfile: (profile: CompanyProfile) => void;
}

const AdminSettings: React.FC<AdminSettingsProps> = ({ navigateTo, language, user, companyProfile, setCompanyProfile }) => {
  const t = translations[language].settings;
  const common = translations[language].common;
  const [formData, setFormData] = useState<CompanyProfile>(() => ({ ...companyProfile }));
  const [isSaving, setIsSaving] = useState(false);
  const [showSuccess, setShowSuccess] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleSave = () => {
    setIsSaving(true);
    
    // Simulate a brief save delay for tactile feedback
    setTimeout(() => {
      setCompanyProfile(formData);
      setIsSaving(false);
      setShowSuccess(true);
      
      // Auto-hide success message after 4 seconds
      setTimeout(() => setShowSuccess(false), 4000);
    }, 600);
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
  };

  const handleLogoUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onloadend = () => {
        setFormData(prev => ({ ...prev, logoUrl: reader.result as string }));
      };
      reader.readAsDataURL(file);
    }
  };

  return (
    <div className="bg-background-light dark:bg-background-dark min-h-[100dvh] text-slate-900 dark:text-white pb-32 relative">
      {/* Global Success Toast */}
      {showSuccess && (
        <div className="fixed top-0 left-0 right-0 z-[100] p-4 safe-area-pt flex justify-center pointer-events-none">
          <div className="bg-green-600 text-white px-6 py-4 rounded-2xl shadow-2xl flex items-center gap-3 animate-in slide-in-from-top-10 fade-in duration-300 pointer-events-auto border border-green-500/20">
            <span className="material-icons">check_circle</span>
            <span className="text-sm font-bold tracking-tight">{t.success}</span>
            <button onClick={() => setShowSuccess(false)} className="ml-2 opacity-70 hover:opacity-100">
              <span className="material-icons text-sm">close</span>
            </button>
          </div>
        </div>
      )}

      <header className="sticky top-0 z-50 bg-background-light/90 dark:bg-background-dark/90 backdrop-blur-md border-b border-slate-300 dark:border-slate-800 px-4 safe-area-pt pb-4 flex items-center gap-3">
        <button onClick={() => navigateTo('profile')} className="p-2 -ml-2 text-primary active:scale-95 transition-transform">
          <span className="material-icons">arrow_back</span>
        </button>
        <h1 className="text-xl font-bold tracking-tight">{t.title}</h1>
      </header>

      <main className="px-4 py-6 space-y-8 max-w-2xl mx-auto">
        {/* Branding Section */}
        <section className="space-y-4">
          <h2 className="text-xs font-black uppercase tracking-widest text-slate-400 px-1">{t.branding}</h2>
          <div className="bg-surface-light dark:bg-surface-dark p-6 rounded-3xl shadow-sm border border-slate-300 dark:border-slate-800 space-y-6">
            <div className="flex flex-col md:flex-row gap-6 items-center">
              <div className="shrink-0">
                <p className="text-[10px] font-black uppercase tracking-widest text-slate-400 mb-2 text-center">{t.logoPreview}</p>
                <div className="w-24 h-24 rounded-2xl bg-slate-50 dark:bg-slate-900 border border-slate-200 dark:border-slate-700 flex items-center justify-center p-4 overflow-hidden relative">
                  {formData.logoUrl ? (
                    <img src={formData.logoUrl} alt="Logo" className="w-full h-full object-contain" />
                  ) : (
                    <span className="material-icons text-slate-200 text-4xl">broken_image</span>
                  )}
                </div>
              </div>
              <div className="flex-grow w-full space-y-4">
                <div className="space-y-1">
                  <label className="text-xs font-bold text-slate-500">{t.companyName}</label>
                  <input 
                    name="name" 
                    value={formData.name} 
                    onChange={handleChange} 
                    className="w-full bg-slate-50 dark:bg-slate-900 border border-slate-200 dark:border-slate-700 rounded-xl py-3.5 px-4 focus:ring-2 focus:ring-primary outline-none transition-all font-medium" 
                  />
                </div>
                <div className="space-y-1">
                  <label className="text-xs font-bold text-slate-500">{t.logoUrl}</label>
                  <div className="flex gap-2">
                    <button 
                      onClick={() => fileInputRef.current?.click()}
                      className="flex-1 bg-primary/10 text-primary py-3.5 rounded-xl font-bold text-sm active:scale-95 transition-all flex items-center justify-center gap-2"
                    >
                      <span className="material-icons">cloud_upload</span>
                      {formData.logoUrl ? t.changeLogo : t.uploadLogo}
                    </button>
                    {formData.logoUrl && (
                      <button 
                        onClick={() => setFormData(prev => ({ ...prev, logoUrl: '' }))}
                        className="w-12 h-12 bg-red-50 dark:bg-red-900/20 text-red-500 rounded-xl flex items-center justify-center active:scale-95 transition-all"
                      >
                        <span className="material-icons">delete</span>
                      </button>
                    )}
                  </div>
                  <input 
                    type="file" 
                    ref={fileInputRef} 
                    onChange={handleLogoUpload} 
                    accept="image/*" 
                    className="hidden" 
                  />
                </div>
              </div>
            </div>
          </div>
        </section>

        {/* Legal & Finance Section */}
        <section className="space-y-4">
          <h2 className="text-xs font-black uppercase tracking-widest text-slate-400 px-1">{t.legal}</h2>
          <div className="bg-white dark:bg-slate-800 p-6 rounded-3xl shadow-sm border border-primary/5 space-y-5">
            <div className="space-y-1">
              <label className="text-xs font-bold text-slate-500">{t.address}</label>
              <textarea 
                name="address" 
                value={formData.address} 
                onChange={handleChange} 
                rows={3} 
                className="w-full bg-slate-50 dark:bg-slate-900 border-none rounded-xl py-3.5 px-4 focus:ring-2 focus:ring-primary outline-none transition-all resize-none text-sm font-medium" 
              />
            </div>
            
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-1">
                <label className="text-xs font-bold text-slate-500">{t.kvk}</label>
                <input 
                  name="kvk" 
                  value={formData.kvk} 
                  onChange={handleChange} 
                  className="w-full bg-slate-50 dark:bg-slate-900 border-none rounded-xl py-3.5 px-4 focus:ring-2 focus:ring-primary outline-none transition-all font-mono" 
                />
              </div>
              <div className="space-y-1">
                <label className="text-xs font-bold text-slate-500">{t.btw}</label>
                <input 
                  name="btw" 
                  value={formData.btw} 
                  onChange={handleChange} 
                  className="w-full bg-slate-50 dark:bg-slate-900 border-none rounded-xl py-3.5 px-4 focus:ring-2 focus:ring-primary outline-none transition-all font-mono" 
                />
              </div>
            </div>

            <div className="space-y-1">
              <label className="text-xs font-bold text-slate-500">{t.iban}</label>
              <input 
                name="iban" 
                value={formData.iban} 
                onChange={handleChange} 
                className="w-full bg-slate-50 dark:bg-slate-900 border-none rounded-xl py-3.5 px-4 focus:ring-2 focus:ring-primary outline-none transition-all font-mono tracking-tighter" 
              />
            </div>

            <div className="space-y-1">
              <label className="text-xs font-bold text-slate-500">{t.footerInfo}</label>
              <textarea 
                name="invoiceFooter" 
                value={formData.invoiceFooter} 
                onChange={handleChange} 
                rows={4} 
                placeholder={t.footerPlaceholder} 
                className="w-full bg-slate-50 dark:bg-slate-900 border-none rounded-xl py-3.5 px-4 focus:ring-2 focus:ring-primary outline-none transition-all resize-none text-sm leading-relaxed" 
              />
            </div>
          </div>
        </section>

        <button 
          onClick={handleSave}
          disabled={isSaving}
          className={`w-full font-bold py-4 rounded-2xl shadow-lg transition-all flex items-center justify-center gap-2 mt-4 active:scale-[0.98] ${
            isSaving 
            ? 'bg-slate-200 text-slate-400 cursor-not-allowed' 
            : 'bg-primary hover:bg-primary/90 text-white shadow-primary/20'
          }`}
        >
          <span className={`material-icons ${isSaving ? 'animate-spin' : ''}`}>
            {isSaving ? 'sync' : 'save'}
          </span>
          {isSaving ? common.loading : common.save}
        </button>
      </main>
    </div>
  );
};

export default AdminSettings;
