/**
 * @license
 * SPDX-License-Identifier: Apache-2.0
 */

import React, { useState, useRef } from "react";
import { 
  Image as ImageIcon, 
  Upload, 
  X, 
  Check, 
  RotateCcw, 
  ShieldCheck, 
  Sparkles, 
  Building2, 
  Link as LinkIcon, 
  CheckCircle2, 
  AlertCircle,
  Eye,
  Camera,
  Layers,
  Award
} from "lucide-react";
import { Employee } from "../types";
import ptMedianLogoDefault from "../assets/images/pt_median_logo_1785758831669.jpg";

interface ChangeCompanyLogoModalProps {
  isOpen: boolean;
  onClose: () => void;
  currentLogo: string;
  onSaveLogo: (newLogoUrl: string) => void;
  currentUser: Employee;
}

// Preset vector & high quality company logos for instant selection
const PRESET_LOGOS = [
  {
    id: "default",
    name: "PT Median Original Logo",
    description: "Logo resmi standar PT Median Enterprise Data",
    url: ptMedianLogoDefault
  },
  {
    id: "futuristic-blue",
    name: "Tech Ecosystem Logo (Cyan Glow)",
    description: "Logo gaya futuristik biru neon untuk divisi IT/CTO",
    url: "https://images.unsplash.com/photo-1618005182384-a83a8bd57fbe?auto=format&fit=crop&w=300&q=80"
  },
  {
    id: "gold-executive",
    name: "Gold Executive Shield",
    description: "Emblem emas elegan untuk holding perusahaan",
    url: "https://images.unsplash.com/photo-1634017839464-5c339ebe3cb4?auto=format&fit=crop&w=300&q=80"
  },
  {
    id: "minimal-dark",
    name: "Minimalist Geometry Dark",
    description: "Desain monokrom modern dan bersih",
    url: "https://images.unsplash.com/photo-1618005182384-a83a8bd57fbe?auto=format&fit=crop&w=300&q=80"
  }
];

export function ChangeCompanyLogoModal({
  isOpen,
  onClose,
  currentLogo,
  onSaveLogo,
  currentUser
}: ChangeCompanyLogoModalProps) {
  const [activeTab, setActiveTab] = useState<"upload" | "url" | "presets">("upload");
  const [previewLogo, setPreviewLogo] = useState<string>(currentLogo);
  const [urlInput, setUrlInput] = useState<string>("");
  const [errorMsg, setErrorMsg] = useState<string | null>(null);
  const [successToast, setSuccessToast] = useState<string | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  // Check authorization level
  const posUpper = (currentUser.position || "").toUpperCase();
  const isAuthorized = 
    posUpper.includes("CEO") || 
    posUpper.includes("DIREKTUR") || 
    posUpper.includes("MANAGER") || 
    posUpper.includes("CTO") || 
    posUpper.includes("ADMIN") ||
    posUpper.includes("HEAD") ||
    posUpper.includes("LEAD");

  if (!isOpen) return null;

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

    if (!file.type.startsWith("image/")) {
      setErrorMsg("File harus berupa gambar (PNG, JPG, SVG, WebP)");
      return;
    }

    if (file.size > 5 * 1024 * 1024) {
      setErrorMsg("Ukuran file maksimal 5MB");
      return;
    }

    const reader = new FileReader();
    reader.onload = () => {
      if (typeof reader.result === "string") {
        setPreviewLogo(reader.result);
      }
    };
    reader.readAsDataURL(file);
  };

  const handleApplyUrl = () => {
    setErrorMsg(null);
    if (!urlInput.trim()) {
      setErrorMsg("Silakan masukkan URL gambar logo yang valid");
      return;
    }
    setPreviewLogo(urlInput.trim());
  };

  const handleResetToDefault = () => {
    setPreviewLogo(ptMedianLogoDefault);
    setUrlInput("");
    setErrorMsg(null);
  };

  const handleSave = () => {
    if (!isAuthorized) {
      setErrorMsg("Anda tidak memiliki wewenang untuk merubah logo perusahaan.");
      return;
    }

    onSaveLogo(previewLogo);
    setSuccessToast("Logo perusahaan berhasil diperbarui secara langsung!");
    setTimeout(() => {
      setSuccessToast(null);
      onClose();
    }, 1200);
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-md overflow-y-auto animate-fadeIn font-mono">
      <div className="bg-[#0a0a0a] border border-[#2a2a2a] rounded-xl w-full max-w-2xl overflow-hidden shadow-2xl text-slate-200 relative">
        
        {/* Header Modal */}
        <div className="p-5 border-b border-[#222] bg-gradient-to-r from-[#121212] via-[#0a0a0a] to-[#121212] flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div className="p-2.5 bg-[#facc15]/10 border border-[#facc15]/30 text-[#facc15] rounded-lg">
              <Building2 className="w-6 h-6 animate-pulse" />
            </div>
            <div>
              <div className="flex items-center gap-2">
                <span className="text-[10px] font-black uppercase px-2 py-0.5 bg-[#facc15] text-black rounded font-mono">
                  BRAND IDENTITY MANAGER
                </span>
                <span className="text-[10px] font-bold text-slate-400 font-mono">
                  EMS FRONTEND DIRECT EDIT
                </span>
              </div>
              <h3 className="text-lg font-black text-white uppercase tracking-tight mt-1">
                Ubah Logo Perusahaan Secara Langsung
              </h3>
            </div>
          </div>

          <button
            type="button"
            onClick={onClose}
            className="p-2 text-slate-400 hover:text-white bg-[#141414] hover:bg-[#222] border border-[#333] rounded-lg transition-colors cursor-pointer"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Content Body */}
        <div className="p-6 space-y-6">

          {/* Authorization status badge */}
          <div className={`p-3.5 rounded-lg border text-xs flex items-center justify-between gap-3 ${
            isAuthorized 
              ? "bg-emerald-500/10 border-emerald-500/30 text-emerald-300"
              : "bg-amber-500/10 border-amber-500/30 text-amber-300"
          }`}>
            <div className="flex items-center gap-2.5">
              <ShieldCheck className="w-5 h-5 shrink-0" />
              <div>
                <strong className="block font-black uppercase">
                  {isAuthorized ? "Wewenang Dikonfirmasi (Akses Disetujui)" : "Mode Pratinjau Terbatas"}
                </strong>
                <p className="text-[11px] opacity-90">
                  Jabatan Pengguna: <strong>{currentUser.name}</strong> ({currentUser.position} • {currentUser.division})
                </p>
              </div>
            </div>
            <span className={`text-[9px] font-black uppercase px-2 py-1 rounded border shrink-0 ${
              isAuthorized ? "bg-emerald-500 text-black border-emerald-400" : "bg-amber-500 text-black border-amber-400"
            }`}>
              {isAuthorized ? "FULL ACCESS" : "READ ONLY"}
            </span>
          </div>

          {/* Live Preview Header Simulation */}
          <div className="space-y-2">
            <label className="text-[11px] font-black uppercase text-slate-400 flex items-center gap-1.5">
              <Eye className="w-3.5 h-3.5 text-[#facc15]" />
              Pratinjau Langsung Tampilan Logo di Header Aplikasi:
            </label>
            <div className="bg-[#0f172a] border border-sky-500/40 p-3 rounded-lg flex items-center justify-between">
              <div className="flex items-center gap-3">
                <div className="relative w-11 h-11 rounded-xl bg-[#081026] border border-sky-400/40 p-1 flex items-center justify-center overflow-hidden shadow-lg shadow-sky-500/30 shrink-0">
                  <img 
                    src={previewLogo} 
                    alt="Pratinjau Logo" 
                    referrerPolicy="no-referrer"
                    className="w-full h-full object-contain rounded-lg"
                    onError={(e) => {
                      (e.target as HTMLElement).style.display = "none";
                    }}
                  />
                </div>
                <div>
                  <div className="flex items-center gap-1.5">
                    <h4 className="text-sm font-black uppercase text-white tracking-tight">
                      EMS MEDIAN
                    </h4>
                    <span className="text-[9px] font-black bg-sky-500/20 text-sky-300 border border-sky-400/40 px-1 rounded uppercase">
                      LIVE
                    </span>
                  </div>
                  <p className="text-[9px] uppercase tracking-wider text-sky-300 font-bold">
                    PT MEDIA EKOSISTEM DIGITAL APLIKASI NASIONAL
                  </p>
                </div>
              </div>

              <span className="text-[10px] text-slate-400 bg-black/40 px-2 py-1 rounded border border-white/10 font-bold">
                Navbar Preview
              </span>
            </div>
          </div>

          {/* Tab Selector for Image Source */}
          <div className="flex items-center border-b border-[#222] text-xs font-bold">
            <button
              type="button"
              onClick={() => setActiveTab("upload")}
              className={`py-2.5 px-4 uppercase tracking-wider flex items-center gap-1.5 border-b-2 transition-all cursor-pointer ${
                activeTab === "upload" 
                  ? "border-[#facc15] text-[#facc15] bg-[#facc15]/5" 
                  : "border-transparent text-slate-400 hover:text-white"
              }`}
            >
              <Upload className="w-3.5 h-3.5" />
              Upload dari Komputer
            </button>
            <button
              type="button"
              onClick={() => setActiveTab("url")}
              className={`py-2.5 px-4 uppercase tracking-wider flex items-center gap-1.5 border-b-2 transition-all cursor-pointer ${
                activeTab === "url" 
                  ? "border-[#facc15] text-[#facc15] bg-[#facc15]/5" 
                  : "border-transparent text-slate-400 hover:text-white"
              }`}
            >
              <LinkIcon className="w-3.5 h-3.5" />
              Input Web URL Gambar
            </button>
            <button
              type="button"
              onClick={() => setActiveTab("presets")}
              className={`py-2.5 px-4 uppercase tracking-wider flex items-center gap-1.5 border-b-2 transition-all cursor-pointer ${
                activeTab === "presets" 
                  ? "border-[#facc15] text-[#facc15] bg-[#facc15]/5" 
                  : "border-transparent text-slate-400 hover:text-white"
              }`}
            >
              <Sparkles className="w-3.5 h-3.5" />
              Koleksi Preset Brand
            </button>
          </div>

          {/* Tab 1: File Upload */}
          {activeTab === "upload" && (
            <div className="space-y-4">
              <input 
                type="file" 
                ref={fileInputRef}
                onChange={handleFileUpload} 
                accept="image/*" 
                className="hidden" 
              />
              
              <div 
                onClick={() => fileInputRef.current?.click()}
                className="border-2 border-dashed border-[#333] hover:border-[#facc15] bg-[#050505] hover:bg-[#0d0d0d] rounded-xl p-8 text-center cursor-pointer transition-all space-y-3 group"
              >
                <div className="w-12 h-12 rounded-full bg-[#facc15]/10 border border-[#facc15]/30 text-[#facc15] flex items-center justify-center mx-auto group-hover:scale-110 transition-transform">
                  <Camera className="w-6 h-6" />
                </div>
                <div>
                  <p className="text-sm font-bold text-white uppercase">
                    Klik atau Seret Gambar Logo ke Sini
                  </p>
                  <p className="text-xs text-slate-400 mt-1">
                    Mendukung format PNG, JPG, WebP, SVG (Maksimal 5MB)
                  </p>
                </div>
                <button
                  type="button"
                  className="px-4 py-1.5 bg-[#1a1a1a] group-hover:bg-[#facc15] text-slate-300 group-hover:text-black border border-[#333] group-hover:border-[#facc15] font-black text-xs uppercase rounded transition-colors"
                >
                  Pilih File Gambar
                </button>
              </div>
            </div>
          )}

          {/* Tab 2: URL Input */}
          {activeTab === "url" && (
            <div className="space-y-3">
              <label className="text-xs font-bold text-slate-300 uppercase block">
                Tautan URL Direct Gambar Logo:
              </label>
              <div className="flex gap-2">
                <input
                  type="url"
                  value={urlInput}
                  onChange={(e) => setUrlInput(e.target.value)}
                  placeholder="https://domain.com/logo-perusahaan.png"
                  className="flex-1 bg-[#050505] border border-[#333] focus:border-[#facc15] px-3.5 py-2 text-xs text-white rounded font-mono outline-none"
                />
                <button
                  type="button"
                  onClick={handleApplyUrl}
                  className="px-4 py-2 bg-[#facc15] hover:bg-yellow-400 text-black font-black text-xs uppercase rounded cursor-pointer transition-colors"
                >
                  Terapkan
                </button>
              </div>
            </div>
          )}

          {/* Tab 3: Presets Gallery */}
          {activeTab === "presets" && (
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
              {PRESET_LOGOS.map((preset) => (
                <div
                  key={preset.id}
                  onClick={() => setPreviewLogo(preset.url)}
                  className={`p-3 rounded-lg border cursor-pointer transition-all flex items-center gap-3 ${
                    previewLogo === preset.url 
                      ? "bg-[#facc15]/10 border-[#facc15] shadow-md shadow-amber-500/10" 
                      : "bg-[#050505] border-[#222] hover:border-[#444]"
                  }`}
                >
                  <div className="w-12 h-12 rounded bg-black border border-[#333] p-1 flex items-center justify-center shrink-0">
                    <img src={preset.url} alt={preset.name} className="w-full h-full object-contain" />
                  </div>
                  <div className="overflow-hidden">
                    <h5 className="text-xs font-bold text-white uppercase line-clamp-1">{preset.name}</h5>
                    <p className="text-[10px] text-slate-400 line-clamp-1">{preset.description}</p>
                  </div>
                </div>
              ))}
            </div>
          )}

          {/* Error Message */}
          {errorMsg && (
            <div className="p-3 bg-rose-500/10 border border-rose-500/30 text-rose-300 rounded text-xs flex items-center gap-2">
              <AlertCircle className="w-4 h-4 shrink-0" />
              <span>{errorMsg}</span>
            </div>
          )}

          {/* Success Toast Notification */}
          {successToast && (
            <div className="p-3 bg-emerald-500/10 border border-emerald-500/40 text-emerald-300 rounded text-xs flex items-center gap-2 animate-bounce">
              <CheckCircle2 className="w-4 h-4 text-emerald-400 shrink-0" />
              <span className="font-bold">{successToast}</span>
            </div>
          )}

        </div>

        {/* Footer Actions */}
        <div className="p-5 border-t border-[#222] bg-[#050505] flex items-center justify-between">
          <button
            type="button"
            onClick={handleResetToDefault}
            className="px-3 py-2 bg-[#111] hover:bg-[#222] text-slate-400 hover:text-white border border-[#333] text-xs font-bold uppercase rounded flex items-center gap-1.5 transition-colors cursor-pointer"
            title="Kembalikan ke Logo Asli PT Median"
          >
            <RotateCcw className="w-3.5 h-3.5" />
            Reset Logo Default
          </button>

          <div className="flex items-center gap-2">
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 bg-[#141414] hover:bg-[#222] text-slate-300 text-xs font-bold uppercase rounded border border-[#333] cursor-pointer"
            >
              Batal
            </button>
            <button
              type="button"
              onClick={handleSave}
              disabled={!isAuthorized}
              className="px-5 py-2 bg-gradient-to-r from-amber-500 to-yellow-500 hover:from-amber-400 hover:to-yellow-400 text-black font-black text-xs uppercase rounded shadow-lg shadow-amber-500/20 disabled:opacity-50 cursor-pointer flex items-center gap-1.5"
            >
              <Check className="w-4 h-4 text-black" />
              Simpan & Terapkan Logo
            </button>
          </div>
        </div>

      </div>
    </div>
  );
}
