'use client';

/**
 * Settings page — Super_Admin only.
 *
 * Provides:
 * - Left sidebar navigation: Account, Logo, Theme
 * - Account section: user info display
 * - Logo section: customer logo upload (to AWS S3 via presigned URL)
 * - Theme section: accent color picker with presets
 *
 * Redirects non-Super_Admin users to /overview.
 */

import { useEffect, useRef, useState } from 'react';
import { useRouter } from 'next/navigation';
import { useAuthStore } from '@/lib/stores/auth-store';
import { useLogoStore } from '@/lib/stores/logo-store';
import { useThemeStore, ACCENT_PRESETS, type AccentColor } from '@/lib/stores/theme-store';
import { useCurrencyStore, CURRENCY_OPTIONS, type CurrencyOption } from '@/lib/stores/currency-store';

const MAX_FILE_SIZE = 2 * 1024 * 1024; // 2 MB
const ACCEPTED_TYPES = ['image/png', 'image/jpeg', 'image/svg+xml', 'image/webp'];

type SettingsTab = 'account' | 'logo' | 'theme' | 'currency';

const TABS: { key: SettingsTab; label: string; icon: React.ReactNode }[] = [
  {
    key: 'account',
    label: 'Account',
    icon: (
      <svg className="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2" />
        <circle cx="12" cy="7" r="4" />
      </svg>
    ),
  },
  {
    key: 'logo',
    label: 'Logo',
    icon: (
      <svg className="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <rect x="3" y="3" width="18" height="18" rx="2" ry="2" />
        <circle cx="8.5" cy="8.5" r="1.5" />
        <polyline points="21 15 16 10 5 21" />
      </svg>
    ),
  },
  {
    key: 'theme',
    label: 'Theme',
    icon: (
      <svg className="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <circle cx="13.5" cy="6.5" r="2.5" />
        <path d="M17.5 10.5a2.5 2.5 0 1 0 0 5" />
        <circle cx="8.5" cy="13.5" r="2.5" />
        <circle cx="13.5" cy="17.5" r="2.5" />
        <path d="M6.5 10.5a2.5 2.5 0 1 0 0-5" />
        <path d="M12 2v1" />
        <path d="M12 21v1" />
      </svg>
    ),
  },
  {
    key: 'currency',
    label: 'Currency',
    icon: (
      <svg className="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <line x1="12" y1="1" x2="12" y2="23" />
        <path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6" />
      </svg>
    ),
  },
];

export default function SettingsPage() {
  const router = useRouter();
  const role = useAuthStore((s) => s.role);
  const user = useAuthStore((s) => s.user);
  const { logoUrl, logoKey, logoHeight, isUploading, setLogo, removeLogo, setUploading, setLogoHeight } = useLogoStore();
  const { accent, setAccent } = useThemeStore();
  const { currency, setCurrency } = useCurrencyStore();

  const [activeTab, setActiveTab] = useState<SettingsTab>('account');
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [preview, setPreview] = useState<string | null>(null);
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);
  const [isDragging, setIsDragging] = useState(false);

  useEffect(() => {
    if (role && role !== 'Super_Admin') {
      router.replace('/overview');
    }
  }, [role, router]);

  if (role !== 'Super_Admin') return null;

  // ── File helpers ────────────────────────────────────────────────────────

  const validateAndPreview = (file: File) => {
    setError(null);
    setSuccess(null);
    if (!ACCEPTED_TYPES.includes(file.type)) { setError('Please upload a PNG, JPG, SVG, or WebP image.'); return; }
    if (file.size > MAX_FILE_SIZE) { setError('File size must be under 2 MB.'); return; }
    setSelectedFile(file);
    const reader = new FileReader();
    reader.onload = () => setPreview(reader.result as string);
    reader.readAsDataURL(file);
  };

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) validateAndPreview(file);
  };

  const handleDrop = (e: React.DragEvent) => { e.preventDefault(); setIsDragging(false); const file = e.dataTransfer.files?.[0]; if (file) validateAndPreview(file); };
  const handleDragOver = (e: React.DragEvent) => { e.preventDefault(); setIsDragging(true); };
  const handleDragLeave = () => setIsDragging(false);

  const handleUpload = async () => {
    if (!selectedFile) return;
    setError(null); setSuccess(null); setUploading(true);
    try {
      const res = await fetch('/api/upload-logo', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ contentType: selectedFile.type, filename: selectedFile.name }) });
      if (!res.ok) { const data = await res.json(); throw new Error(data.error || 'Failed to get upload URL'); }
      const { presignedUrl, publicUrl, key } = await res.json();
      const uploadRes = await fetch(presignedUrl, { method: 'PUT', headers: { 'Content-Type': selectedFile.type }, body: selectedFile });
      if (!uploadRes.ok) throw new Error('Failed to upload file to S3');
      if (logoKey) { await fetch('/api/upload-logo', { method: 'DELETE', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ key: logoKey }) }).catch(() => {}); }
      setLogo(publicUrl, key); setSelectedFile(null); setPreview(null); setSuccess('Logo uploaded successfully.');
    } catch (err) { setError(err instanceof Error ? err.message : 'Upload failed.'); } finally { setUploading(false); }
  };

  const handleRemove = async () => {
    setError(null); setSuccess(null);
    if (logoKey) { setUploading(true); try { await fetch('/api/upload-logo', { method: 'DELETE', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ key: logoKey }) }); } catch {} finally { setUploading(false); } }
    removeLogo(); setSelectedFile(null); setPreview(null); if (fileInputRef.current) fileInputRef.current.value = ''; setSuccess('Logo removed.');
  };

  const handleCancelPreview = () => { setSelectedFile(null); setPreview(null); setError(null); if (fileInputRef.current) fileInputRef.current.value = ''; };

  // ── Render ──────────────────────────────────────────────────────────────

  return (
    <div className="flex gap-6 min-h-[calc(100vh-8rem)]">
      {/* Settings sidebar */}
      <nav className="w-48 flex-shrink-0">
        <h1 className="text-xl font-bold text-divisi-text-primary mb-4">Settings</h1>
        <div className="flex flex-col gap-1">
          {TABS.map((tab) => (
            <button
              key={tab.key}
              type="button"
              onClick={() => setActiveTab(tab.key)}
              className={`
                flex items-center gap-2.5 rounded-lg px-3 py-2.5 text-sm font-medium transition-colors duration-150 w-full text-left
                ${activeTab === tab.key
                  ? 'bg-divisi-accent/10 text-divisi-accent'
                  : 'text-divisi-text-secondary hover:text-divisi-text-primary hover:bg-white/5'
                }
              `}
            >
              {tab.icon}
              {tab.label}
            </button>
          ))}
        </div>
      </nav>

      {/* Content area */}
      <div className="flex-1 max-w-2xl">
        {/* ── Account Tab ──────────────────────────────────────────────── */}
        {activeTab === 'account' && (
          <section className="space-y-6">
            <div>
              <h2 className="text-lg font-semibold text-divisi-text-primary">Account</h2>
              <p className="mt-1 text-sm text-divisi-text-secondary">Your account information.</p>
            </div>
            <div className="rounded-xl border border-divisi-border bg-divisi-card p-6 space-y-4">
              <div>
                <label className="text-xs font-medium text-divisi-text-secondary uppercase tracking-wider">Name</label>
                <p className="mt-1 text-sm text-divisi-text-primary">{user?.name ?? 'N/A'}</p>
              </div>
              <div>
                <label className="text-xs font-medium text-divisi-text-secondary uppercase tracking-wider">Role</label>
                <p className="mt-1 text-sm text-divisi-text-primary">{role?.replace(/_/g, ' ') ?? 'N/A'}</p>
              </div>
              <div>
                <label className="text-xs font-medium text-divisi-text-secondary uppercase tracking-wider">Session</label>
                <p className="mt-1 text-sm text-divisi-text-primary">Active (sessionStorage)</p>
              </div>
            </div>
          </section>
        )}

        {/* ── Logo Tab ─────────────────────────────────────────────────── */}
        {activeTab === 'logo' && (
          <section className="space-y-6">
            <div>
              <h2 className="text-lg font-semibold text-divisi-text-primary">Customer Logo</h2>
              <p className="mt-1 text-sm text-divisi-text-secondary">Upload your organization's logo. It will appear in the header.</p>
            </div>

            <div className="rounded-xl border border-divisi-border bg-divisi-card p-6">
              {logoUrl && !preview && (
                <div className="mb-5 flex items-center gap-4">
                  <div className="flex items-center justify-center rounded-lg border border-divisi-border bg-divisi-bg p-4">
                    <img src={logoUrl} alt="Current customer logo" className="max-h-16 max-w-[200px] object-contain" />
                  </div>
                  <div className="flex flex-col gap-2">
                    <span className="text-xs text-divisi-text-secondary">Current logo</span>
                    <button type="button" onClick={handleRemove} disabled={isUploading} className="text-sm text-red-400 hover:text-red-300 transition-colors disabled:opacity-50">Remove</button>
                  </div>
                </div>
              )}

              <div
                onDrop={handleDrop} onDragOver={handleDragOver} onDragLeave={handleDragLeave}
                onClick={() => fileInputRef.current?.click()}
                className={`flex flex-col items-center justify-center rounded-lg border-2 border-dashed p-8 cursor-pointer transition-colors duration-150 ${isDragging ? 'border-divisi-accent bg-divisi-accent/5' : 'border-divisi-border hover:border-divisi-accent/50'}`}
              >
                {preview ? (
                  <img src={preview} alt="Logo preview" className="max-h-20 max-w-full object-contain" />
                ) : (
                  <>
                    <svg className="mb-3 h-10 w-10 text-divisi-text-secondary" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                      <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" /><polyline points="17 8 12 3 7 8" /><line x1="12" y1="3" x2="12" y2="15" />
                    </svg>
                    <p className="text-sm text-divisi-text-secondary">Drop an image here or click to browse</p>
                  </>
                )}
                <input ref={fileInputRef} type="file" accept=".png,.jpg,.jpeg,.svg,.webp" onChange={handleFileChange} className="hidden" aria-label="Upload logo file" />
              </div>
              <p className="mt-2 text-xs text-divisi-text-secondary">PNG, JPG, SVG, or WebP · Max 2 MB</p>

              {error && <p className="mt-3 text-sm text-red-400">{error}</p>}
              {success && <p className="mt-3 text-sm text-green-400">{success}</p>}

              {preview && (
                <div className="mt-4 flex gap-3">
                  <button type="button" onClick={handleUpload} disabled={isUploading} className={`rounded-lg px-5 py-2 text-sm font-semibold transition-colors ${isUploading ? 'bg-divisi-accent/30 text-divisi-bg/50 cursor-not-allowed' : 'bg-divisi-accent text-divisi-bg hover:bg-divisi-accent-hover cursor-pointer'}`}>
                    {isUploading ? 'Uploading…' : 'Upload'}
                  </button>
                  <button type="button" onClick={handleCancelPreview} disabled={isUploading} className="rounded-lg px-4 py-2 text-sm text-divisi-text-secondary hover:text-divisi-text-primary hover:bg-white/5 transition-colors disabled:opacity-50">Cancel</button>
                </div>
              )}
            </div>

            {/* Logo size in header */}
            {logoUrl && (
              <div className="rounded-xl border border-divisi-border bg-divisi-card p-6 mt-6">
                <h3 className="text-sm font-medium text-divisi-text-primary mb-4">Logo Size in Header</h3>
                <div className="flex items-center gap-4">
                  <span className="text-xs text-divisi-text-secondary w-8">S</span>
                  <input
                    type="range"
                    min="20"
                    max="48"
                    value={logoHeight}
                    onChange={(e) => setLogoHeight(Number(e.target.value))}
                    className="flex-1 h-2 rounded-full appearance-none bg-divisi-border cursor-pointer accent-divisi-accent"
                  />
                  <span className="text-xs text-divisi-text-secondary w-8">L</span>
                  <span className="text-xs text-divisi-text-secondary ml-2 w-10">{logoHeight}px</span>
                </div>
                <div className="mt-4 flex items-center gap-3 rounded-lg bg-divisi-bg p-3">
                  <span className="text-xs text-divisi-text-secondary">Preview:</span>
                  <img src={logoUrl} alt="Logo preview" style={{ height: `${logoHeight}px` }} className="max-w-[160px] object-contain" />
                </div>
              </div>
            )}
          </section>
        )}

        {/* ── Theme Tab ────────────────────────────────────────────────── */}
        {activeTab === 'theme' && (
          <section className="space-y-6">
            <div>
              <h2 className="text-lg font-semibold text-divisi-text-primary">Theme</h2>
              <p className="mt-1 text-sm text-divisi-text-secondary">Customize the accent color used across the platform.</p>
            </div>

            <div className="rounded-xl border border-divisi-border bg-divisi-card p-6">
              <h3 className="text-sm font-medium text-divisi-text-primary mb-4">Accent Color</h3>
              <div className="grid grid-cols-4 gap-3">
                {ACCENT_PRESETS.map((preset) => {
                  const isSelected = accent.name === preset.name;
                  return (
                    <button
                      key={preset.name}
                      type="button"
                      onClick={() => setAccent(preset)}
                      className={`
                        flex flex-col items-center gap-2 rounded-xl p-4 border-2 transition-all duration-150
                        ${isSelected
                          ? 'border-divisi-accent bg-divisi-accent/10'
                          : 'border-divisi-border hover:border-divisi-text-secondary/30'
                        }
                      `}
                    >
                      <div
                        className={`h-8 w-8 rounded-full ring-2 ring-offset-2 ring-offset-divisi-card ${isSelected ? 'ring-current' : 'ring-transparent'}`}
                        style={{
                          backgroundColor: preset.value,
                          color: preset.value,
                        }}
                      />
                      <span className={`text-xs font-medium ${isSelected ? 'text-divisi-accent' : 'text-divisi-text-secondary'}`}>
                        {preset.name}
                      </span>
                      {isSelected && (
                        <svg className="h-3.5 w-3.5 text-divisi-accent" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
                          <polyline points="20 6 9 17 4 12" />
                        </svg>
                      )}
                    </button>
                  );
                })}
              </div>

              {/* Custom color picker */}
              <div className="mt-5 pt-5 border-t border-divisi-border">
                <h3 className="text-sm font-medium text-divisi-text-primary mb-3">Custom Color</h3>
                <div className="flex items-center gap-4">
                  <label className="relative cursor-pointer group">
                    <input
                      type="color"
                      value={accent.name === 'Custom' ? accent.value : '#c8e600'}
                      onChange={(e) => {
                        const hex = e.target.value;
                        // Generate hover (lighter) and light-mode (darker) variants
                        const r = parseInt(hex.slice(1, 3), 16);
                        const g = parseInt(hex.slice(3, 5), 16);
                        const b = parseInt(hex.slice(5, 7), 16);
                        // Hover: lighten by 20%
                        const lighten = (v: number) => Math.min(255, Math.round(v + (255 - v) * 0.2));
                        const hoverHex = `#${lighten(r).toString(16).padStart(2, '0')}${lighten(g).toString(16).padStart(2, '0')}${lighten(b).toString(16).padStart(2, '0')}`;
                        // Light mode: darken by 30%
                        const darken = (v: number) => Math.max(0, Math.round(v * 0.7));
                        const darkHex = `#${darken(r).toString(16).padStart(2, '0')}${darken(g).toString(16).padStart(2, '0')}${darken(b).toString(16).padStart(2, '0')}`;
                        // Light hover: darken by 15%
                        const darkenLight = (v: number) => Math.max(0, Math.round(v * 0.85));
                        const darkHoverHex = `#${darkenLight(r).toString(16).padStart(2, '0')}${darkenLight(g).toString(16).padStart(2, '0')}${darkenLight(b).toString(16).padStart(2, '0')}`;
                        setAccent({ name: 'Custom', value: hex, hover: hoverHex, light: darkHex, lightHover: darkHoverHex });
                      }}
                      className="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
                      aria-label="Pick a custom accent color"
                    />
                    <div
                      className="h-10 w-10 rounded-full border-2 border-divisi-border group-hover:border-divisi-text-secondary transition-colors flex items-center justify-center"
                      style={{ backgroundColor: accent.name === 'Custom' ? accent.value : 'transparent' }}
                    >
                      {accent.name !== 'Custom' && (
                        <svg className="h-5 w-5 text-divisi-text-secondary" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                          <line x1="12" y1="5" x2="12" y2="19" />
                          <line x1="5" y1="12" x2="19" y2="12" />
                        </svg>
                      )}
                    </div>
                  </label>
                  <div>
                    <p className="text-sm text-divisi-text-primary">
                      {accent.name === 'Custom' ? accent.value.toUpperCase() : 'Pick any color'}
                    </p>
                    <p className="text-xs text-divisi-text-secondary">Click the circle to open the color picker</p>
                  </div>
                </div>
              </div>

              <div className="mt-6 rounded-lg bg-divisi-bg p-4">
                <p className="text-xs text-divisi-text-secondary mb-2">Preview</p>
                <div className="flex items-center gap-3">
                  <div className="h-3 w-3 rounded-full bg-divisi-accent" />
                  <span className="text-sm text-divisi-accent font-medium">Active accent color</span>
                  <button className="ml-auto rounded-lg bg-divisi-accent px-3 py-1.5 text-xs font-semibold text-divisi-bg">
                    Sample Button
                  </button>
                </div>
              </div>
            </div>
          </section>
        )}

        {/* ── Currency Tab ─────────────────────────────────────────────── */}
        {activeTab === 'currency' && (
          <section className="space-y-6">
            <div>
              <h2 className="text-lg font-semibold text-divisi-text-primary">Currency</h2>
              <p className="mt-1 text-sm text-divisi-text-secondary">Select the currency used for financial values across the platform.</p>
            </div>

            <div className="rounded-xl border border-divisi-border bg-divisi-card p-6">
              <h3 className="text-sm font-medium text-divisi-text-primary mb-4">Display Currency</h3>
              <div className="grid grid-cols-2 gap-3">
                {CURRENCY_OPTIONS.map((option) => {
                  const isSelected = currency.code === option.code;
                  return (
                    <button
                      key={option.code}
                      type="button"
                      onClick={() => setCurrency(option)}
                      className={`
                        flex items-center gap-3 rounded-xl p-4 border-2 transition-all duration-150 text-left
                        ${isSelected
                          ? 'border-divisi-accent bg-divisi-accent/10'
                          : 'border-divisi-border hover:border-divisi-text-secondary/30'
                        }
                      `}
                    >
                      <span className={`text-lg font-bold min-w-[3rem] ${isSelected ? 'text-divisi-accent' : 'text-divisi-text-primary'}`}>
                        {option.symbol}
                      </span>
                      <div className="flex flex-col">
                        <span className={`text-sm font-medium ${isSelected ? 'text-divisi-accent' : 'text-divisi-text-primary'}`}>
                          {option.code}
                        </span>
                        <span className="text-xs text-divisi-text-secondary">{option.name}</span>
                      </div>
                      {isSelected && (
                        <svg className="h-4 w-4 text-divisi-accent ml-auto flex-shrink-0" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
                          <polyline points="20 6 9 17 4 12" />
                        </svg>
                      )}
                    </button>
                  );
                })}
              </div>

              <div className="mt-6 rounded-lg bg-divisi-bg p-4">
                <p className="text-xs text-divisi-text-secondary mb-2">Preview</p>
                <div className="flex items-center gap-3">
                  <span className="text-sm text-divisi-text-primary font-medium">
                    {new Intl.NumberFormat('en-US', { style: 'currency', currency: currency.code, minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(1234567.89)}
                  </span>
                  <span className="text-xs text-divisi-text-secondary">— sample formatted value</span>
                </div>
              </div>
            </div>
          </section>
        )}
      </div>
    </div>
  );
}
