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

import React, { useState, useEffect, useMemo } from "react";
import { Employee, TimelineEvent } from "../types";
import { DIVISION_LIST, POSITION_LIST } from "../data";
import { Upload, X, Save, User, Calendar, CreditCard, ShieldAlert, Sparkles, RefreshCw, Wifi, WifiOff, AlertTriangle, CheckCircle2, Edit3 } from "lucide-react";

interface EmployeeFormProps {
  employee?: Employee | null; // If editing
  employees: Employee[]; // To select reportingTo (Supervisor)
  onSave: (emp: Employee) => void;
  onCancel: () => void;
  isLiveMode?: boolean;
  backendStatus?: 'connected' | 'connecting' | 'failed' | 'simulated';
  backendUrl?: string;
}

export default function EmployeeForm({ 
  employee, 
  employees, 
  onSave, 
  onCancel,
  isLiveMode = false,
  backendStatus = "simulated",
  backendUrl = "http://127.0.0.1:8000"
}: EmployeeFormProps) {
  // Form State
  const [name, setName] = useState("");
  const [nik, setNik] = useState("");
  const [customNip, setCustomNip] = useState("");
  const [isCustomNipEnabled, setIsCustomNipEnabled] = useState(false);
  const [gender, setGender] = useState<"L" | "P">("L");
  const [birthPlace, setBirthPlace] = useState("");
  const [birthDate, setBirthDate] = useState("");
  const [tmtKerja, setTmtKerja] = useState("");
  const [division, setDivision] = useState("");
  const [position, setPosition] = useState("");
  const [status, setStatus] = useState<Employee["status"]>("Aktif");
  const [reportingTo, setReportingTo] = useState("");
  const [phone, setPhone] = useState("");
  const [email, setEmail] = useState("");
  const [address, setAddress] = useState("");
  const [photoUrl, setPhotoUrl] = useState("");
  const [kpiScore, setKpiScore] = useState(80);

  // Validation feedback state
  const [errors, setErrors] = useState<Record<string, string>>({});

  // Gemini AI Smart Input State
  const [aiRawText, setAiRawText] = useState("");
  const [isAiParsing, setIsAiParsing] = useState(false);
  const [aiParseError, setAiParseError] = useState<string | null>(null);
  const [aiParseSuccess, setAiParseSuccess] = useState<string | null>(null);

  const handleAiParse = async () => {
    if (!aiRawText.trim()) return;
    setIsAiParsing(true);
    setAiParseError(null);
    setAiParseSuccess(null);
    try {
      const response = await fetch("/api/gemini/parse-employee", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ text: aiRawText }),
      });

      if (!response.ok) {
        throw new Error(`Gagal menghubungi server AI (Status ${response.status})`);
      }

      const data = await response.json();
      if (data.employee) {
        const emp = data.employee;
        if (emp.name) setName(emp.name);
        if (emp.nik) setNik(emp.nik);
        if (emp.gender) setGender(emp.gender === "P" ? "P" : "L");
        if (emp.birthPlace) setBirthPlace(emp.birthPlace);
        if (emp.birthDate) setBirthDate(emp.birthDate);
        if (emp.tmtKerja) setTmtKerja(emp.tmtKerja);
        
        if (emp.division) {
          const foundDiv = DIVISION_LIST.find(d => d.toLowerCase() === emp.division.toLowerCase()) || emp.division;
          setDivision(foundDiv);
        }
        if (emp.position) {
          const foundPos = POSITION_LIST.find(p => p.toLowerCase() === emp.position.toLowerCase()) || emp.position;
          setPosition(foundPos);
        }
        if (emp.phone) setPhone(emp.phone);
        if (emp.email) setEmail(emp.email);
        if (emp.address) setAddress(emp.address);
        if (emp.kpiScore !== undefined) setKpiScore(Number(emp.kpiScore) || 80);

        setAiParseSuccess("Berhasil mengekstrak biodata pegawai! Field formulir di bawah telah diisi.");
      } else {
        throw new Error("Format respon server tidak didukung.");
      }
    } catch (err: any) {
      console.error(err);
      setAiParseError(err.message || "Gagal memproses data.");
    } finally {
      setIsAiParsing(false);
    }
  };

  // Populate data when editing
  useEffect(() => {
    if (employee) {
      setName(employee.name);
      setNik(employee.nik);
      setCustomNip(employee.nip);
      setIsCustomNipEnabled(true);
      setGender(employee.gender);
      setBirthPlace(employee.birthPlace || "");
      setBirthDate(employee.birthDate);
      setTmtKerja(employee.tmtKerja);
      setDivision(employee.division);
      setPosition(employee.position);
      setStatus(employee.status);
      setReportingTo(employee.reportingTo || "none");
      setPhone(employee.phone || "");
      setEmail(employee.email || "");
      setAddress(employee.address || "");
      setPhotoUrl(employee.photoUrl || "");
      setKpiScore(employee.kpiScore || 80);
    } else {
      // Defaults for Create
      setName("");
      setNik("");
      setCustomNip("");
      setIsCustomNipEnabled(false);
      setGender("L");
      setBirthPlace("");
      setBirthDate("1995-01-01");
      setTmtKerja(new Date().toISOString().split("T")[0]);
      setDivision(DIVISION_LIST[5]); // Default: Operations
      setPosition(POSITION_LIST[5]); // Default: Staff
      setStatus("Kontrak");
      setReportingTo("none");
      setPhone("");
      setEmail("");
      setAddress("");
      setPhotoUrl("");
      setKpiScore(80);
    }
    setErrors({});
  }, [employee]);

  // AUTO AGE (Umur) Calculation
  const autoAge = useMemo(() => {
    if (!birthDate) return 0;
    const bDate = new Date(birthDate);
    const today = new Date();
    let age = today.getFullYear() - bDate.getFullYear();
    const m = today.getMonth() - bDate.getMonth();
    if (m < 0 || (m === 0 && today.getDate() < bDate.getDate())) {
      age--;
    }
    return age >= 0 ? age : 0;
  }, [birthDate]);

  // AUTO MASA KERJA (Service Period) Calculation
  const autoTenure = useMemo(() => {
    if (!tmtKerja) return { years: 0, months: 0, text: "0 Tahun 0 Bulan" };
    const joinDate = new Date(tmtKerja);
    const today = new Date();
    
    let months = (today.getFullYear() - joinDate.getFullYear()) * 12 + (today.getMonth() - joinDate.getMonth());
    if (today.getDate() < joinDate.getDate()) {
      months--;
    }
    if (months < 0) return { years: 0, months: 0, text: "0 Bulan (Belum Mulai)" };

    const years = Math.floor(months / 12);
    const remainingMonths = months % 12;
    return {
      years,
      months: remainingMonths,
      text: `${years} Tahun ${remainingMonths} Bulan`
    };
  }, [tmtKerja]);

  // AUTO NIP GENERATOR formula: birthYear + joinYear + unique_serial
  const autoNip = useMemo(() => {
    if (!birthDate || !tmtKerja) return "199020260000";
    
    // If editing, preserve original NIP if exists
    if (employee && employee.nip) return employee.nip;

    try {
      const birthYear = new Date(birthDate).getFullYear().toString();
      const joinYear = new Date(tmtKerja).getFullYear().toString();
      
      // Generate a semi-random or sequential index based on current employee count
      const seq = (employees.length + 1).toString().padStart(4, "0");
      return `${birthYear}${joinYear}${seq}`;
    } catch {
      return "199020260001";
    }
  }, [birthDate, tmtKerja, employee, employees]);

  // Effective NIP used in employee object
  const effectiveNip = useMemo(() => {
    if (isCustomNipEnabled && customNip.trim()) return customNip.trim();
    if (employee && employee.nip) return employee.nip;
    return autoNip;
  }, [isCustomNipEnabled, customNip, employee, autoNip]);

  // REAL-TIME DUPLICATE DETECTOR FOR NIK
  const duplicateNikMatch = useMemo(() => {
    const trimmedNik = nik.trim();
    if (!trimmedNik) return null;
    return employees.find(e => e.id !== employee?.id && e.nik && e.nik.trim() === trimmedNik);
  }, [nik, employees, employee]);

  // REAL-TIME DUPLICATE DETECTOR FOR NIP
  const duplicateNipMatch = useMemo(() => {
    const trimmedNip = effectiveNip.trim();
    if (!trimmedNip) return null;
    return employees.find(e => e.id !== employee?.id && e.nip && e.nip.trim() === trimmedNip);
  }, [effectiveNip, employees, employee]);

  // Photo upload handler to base64
  const handlePhotoUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      if (file.size > 2 * 1024 * 1024) {
        setErrors(prev => ({ ...prev, photo: "Ukuran file foto maksimal adalah 2MB." }));
        return;
      }
      const reader = new FileReader();
      reader.onloadend = () => {
        setPhotoUrl(reader.result as string);
        setErrors(prev => {
          const copy = { ...prev };
          delete copy.photo;
          return copy;
        });
      };
      reader.readAsDataURL(file);
    }
  };

  // Field validations
  const validateForm = () => {
    const tempErrors: Record<string, string> = {};
    if (!name.trim()) tempErrors.name = "Nama lengkap wajib diisi.";
    
    if (!nik.trim()) {
      tempErrors.nik = "NIK KTP wajib diisi.";
    } else if (!/^\d+$/.test(nik)) {
      tempErrors.nik = "NIK KTP harus berupa angka saja.";
    } else if (nik.length < 8 || nik.length > 20) {
      tempErrors.nik = "NIK KTP harus berukuran antara 8 hingga 20 digit.";
    } else if (duplicateNikMatch) {
      tempErrors.nik = `DUPLIKASI DETECTED: NIK ${nik} sudah terdaftar atas nama ${duplicateNikMatch.name} (${duplicateNikMatch.division}).`;
    }

    if (!effectiveNip.trim()) {
      tempErrors.nip = "NIP internal wajib diisi.";
    } else if (duplicateNipMatch) {
      tempErrors.nip = `DUPLIKASI DETECTED: NIP ${effectiveNip} sudah digunakan oleh ${duplicateNipMatch.name} (${duplicateNipMatch.division}).`;
    }

    if (!birthPlace.trim()) tempErrors.birthPlace = "Tempat lahir wajib diisi.";
    if (!birthDate) tempErrors.birthDate = "Tanggal lahir wajib diisi.";
    if (!tmtKerja) tempErrors.tmtKerja = "Tanggal mulai kerja (TMT) wajib diisi.";
    
    if (phone.trim() && !/^\+?[0-9\s-]{8,15}$/.test(phone)) {
      tempErrors.phone = "Nomor HP tidak valid (8-15 digit).";
    }

    if (email.trim() && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      tempErrors.email = "Alamat email tidak valid.";
    }

    setErrors(tempErrors);
    return Object.keys(tempErrors).length === 0;
  };

  // Helper to quickly auto-populate valid mock data for testing
  const handleAutoFill = () => {
    const firstNames = ["Rian", "Budi", "Candra", "Siti", "Eka", "Feri", "Gita", "Hendra", "Indah", "Joko"];
    const lastNames = ["Pratama", "Wibowo", "Sari", "Lestari", "Kusuma", "Ariyanto", "Hidayat", "Nugroho"];
    const randomName = `${firstNames[Math.floor(Math.random() * firstNames.length)]} ${lastNames[Math.floor(Math.random() * lastNames.length)]}`;
    const randomNik = "32" + Math.floor(10000000000000 + Math.random() * 90000000000000).toString();
    const cities = ["Jakarta", "Bandung", "Surabaya", "Yogyakarta", "Semarang", "Medan", "Makassar", "Palembang"];
    const randomCity = cities[Math.floor(Math.random() * cities.length)];
    
    const birthYear = Math.floor(1980 + Math.random() * 23);
    const birthMonth = Math.floor(1 + Math.random() * 12).toString().padStart(2, '0');
    const birthDay = Math.floor(1 + Math.random() * 28).toString().padStart(2, '0');
    const randomBirthDate = `${birthYear}-${birthMonth}-${birthDay}`;

    const joinYear = Math.floor(2018 + Math.random() * 8);
    const joinMonth = Math.floor(1 + Math.random() * 12).toString().padStart(2, '0');
    const joinDay = Math.floor(1 + Math.random() * 28).toString().padStart(2, '0');
    const randomJoinDate = `${joinYear}-${joinMonth}-${joinDay}`;

    setName(randomName);
    setNik(randomNik);
    setBirthPlace(randomCity);
    setBirthDate(randomBirthDate);
    setTmtKerja(randomJoinDate);
    setPhone("0812" + Math.floor(10000000 + Math.random() * 90000000).toString());
    setEmail(`${randomName.toLowerCase().replace(/\s+/g, '.')}@example.com`);
    setAddress(`Jl. Jenderal Sudirman No. ${Math.floor(1 + Math.random() * 150)}, ${randomCity}`);
    setErrors({});
  };

  // Save submit
  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!validateForm()) {
      const formEl = document.getElementById("employee-form-container");
      if (formEl) {
        formEl.scrollIntoView({ behavior: "smooth", block: "start" });
      }
      return;
    }

    // Build the base timeline list
    let initialTimeline: TimelineEvent[] = employee?.timeline ? [...employee.timeline] : [
      {
        id: `tl-${Math.random().toString(36).substr(2, 5)}`,
        date: tmtKerja,
        title: "Pengangkatan Pegawai",
        description: `Terdaftar resmi sebagai ${position} di Divisi ${division}`,
        type: "career" as const
      }
    ];

    // AUTO-LOG FOR RESIGN OR PENSIUN
    const isResignOrRetire = status === "Resigned" || status === "Resign" || status === "Pensiun";
    const statusChanged = !employee || employee.status !== status;
    const todayStr = new Date().toISOString().split("T")[0];

    if (isResignOrRetire && statusChanged) {
      const isResign = status === "Resigned" || status === "Resign";
      const autoTitle = isResign ? "Pemberhentian / Resign Pegawai" : "Masa Purna Bakti / Pensiun";
      const autoDesc = isResign
        ? `Log Otomatis: Pegawai dinyatakan resmi Pengunduran Diri / Resign dari posisi ${position} (Divisi ${division}). Status diperbarui ke ${status}.`
        : `Log Otomatis: Pegawai memasuki masa Purna Bakti / Pensiun dari posisi ${position} (Divisi ${division}). Status diperbarui ke Pensiun.`;

      const alreadyLogged = initialTimeline.some(t => t.title === autoTitle && t.date === todayStr);
      if (!alreadyLogged) {
        initialTimeline.unshift({
          id: `tl-auto-${Date.now()}`,
          date: todayStr,
          title: autoTitle,
          description: autoDesc,
          type: (isResign ? "disciplinary" : "career") as TimelineEvent["type"]
        });
      }
    }

    // Build the new/updated employee object
    const savedEmployee: Employee = {
      id: employee?.id || `emp-${Math.random().toString(36).substr(2, 9)}`,
      nip: effectiveNip,
      nik: nik.trim(),
      name: name.trim(),
      photoUrl,
      division,
      position,
      status,
      tmtKerja,
      birthPlace: birthPlace.trim(),
      birthDate,
      reportingTo: reportingTo === "none" ? "" : reportingTo,
      phone: phone.trim(),
      email: email.trim(),
      address: address.trim(),
      gender,
      kpiScore: Number(kpiScore),
      riwayatJabatan: employee?.riwayatJabatan || [
        {
          id: `rj-${Math.random().toString(36).substr(2, 5)}`,
          date: tmtKerja,
          type: "Pengangkatan",
          position,
          division,
          note: `Awal masuk kerja (TMT)`
        }
      ],
      riwayatPendidikan: employee?.riwayatPendidikan || [],
      riwayatPelatihan: employee?.riwayatPelatihan || [],
      riwayatSK: employee?.riwayatSK || [
        {
          id: `sk-${Math.random().toString(36).substr(2, 5)}`,
          date: tmtKerja,
          type: "SK Pengangkatan",
          skNumber: `SK-${autoNip}-INIT`,
          effectiveDate: tmtKerja
        }
      ],
      riwayatKPI: employee?.riwayatKPI || [],
      riwayatReward: employee?.riwayatReward || [],
      riwayatPunishment: employee?.riwayatPunishment || [],
      timeline: initialTimeline,
      documents: employee?.documents || []
    };

    onSave(savedEmployee);
  };

  // List potential supervisors: anybody who holds higher position or other employees
  const supervisorsList = useMemo(() => {
    return employees.filter(e => e.id !== employee?.id);
  }, [employees, employee]);

  return (
    <div className="bg-[#0a0a0a] border border-[#222] rounded-none p-6 max-w-4xl mx-auto" id="employee-form-container">
      <div className="flex items-center justify-between border-b border-[#222] pb-4 mb-6">
        <div>
          <h3 className="text-lg font-black text-[#facc15] uppercase tracking-wider" id="form-title">
            {employee ? "Ubah Data Induk Pegawai" : "Registrasi Pegawai Baru"}
          </h3>
          <p className="text-xs text-slate-500 font-mono uppercase mt-1">Master Human Capital Management — Tahap 1</p>
        </div>
        <div className="flex items-center gap-3">
          {!employee && (
            <button
              type="button"
              onClick={handleAutoFill}
              className="bg-purple-950/40 hover:bg-purple-900/60 text-purple-300 border border-purple-500/30 px-3 py-1.5 text-[10px] font-mono uppercase tracking-wider rounded-none transition-colors"
              title="Isi form secara otomatis dengan data simulasi yang valid"
            >
              ⚡ Isi Demo Data
            </button>
          )}
          <button 
            type="button"
            onClick={onCancel}
            className="text-slate-400 hover:text-white rounded-none p-1.5 hover:bg-[#111] transition-colors"
          >
            <X className="w-5 h-5" />
          </button>
        </div>
      </div>

      {/* Live Sync / Simulation Mode Status Banner */}
      <div className="mb-6">
        {isLiveMode && backendStatus === "connected" ? (
          <div className="bg-emerald-950/30 border border-emerald-500/30 p-4 flex items-start gap-3">
            <Wifi className="w-5 h-5 text-emerald-400 mt-0.5 flex-shrink-0 animate-pulse" />
            <div>
              <h4 className="text-xs font-black text-emerald-300 uppercase tracking-wider">🟢 Live Sync Aktif</h4>
              <p className="text-[11px] text-slate-300 mt-1 leading-relaxed">
                Pegawai ini akan langsung disimpan secara permanen di Database Django Anda di <strong className="text-white font-mono">{backendUrl}</strong> saat Anda mengklik tombol Simpan di bawah.
              </p>
            </div>
          </div>
        ) : (
          <div className="bg-amber-950/40 border border-amber-500/40 p-4 flex items-start gap-3">
            <WifiOff className="w-5 h-5 text-amber-500 mt-0.5 flex-shrink-0" />
            <div>
              <h4 className="text-xs font-black text-amber-400 uppercase tracking-wider">⚠️ Mode Simulasi (Offline)</h4>
              <p className="text-[11px] text-slate-300 mt-1 leading-relaxed">
                Karena browser memblokir request langsung ke <code className="text-amber-300 font-mono">http://127.0.0.1:8000</code> karena aturan Mixed Content (HTTPS ke HTTP), pegawai baru ini <strong className="text-amber-400">HANYA tersimpan secara lokal di memori browser Anda</strong> dan <strong className="text-rose-400">TIDAK masuk ke database Django</strong>.
              </p>
              <p className="text-[11px] text-slate-400 mt-2">
                💡 <strong>Solusi:</strong> Gunakan HTTPS Tunnel (seperti Ngrok atau Localtunnel) untuk mendapatkan alamat HTTPS aman, salin ke kolom <strong>Base URL</strong> di atas, dan klik <strong>Connect Live</strong> sebelum mendaftarkan pegawai!
              </p>
            </div>
          </div>
        )}
      </div>

      {/* AI Smart Input Panel */}
      {!employee && (
        <div className="bg-[#0e0e0e] border border-[#facc15]/30 p-5 mb-6 font-sans">
          <div className="flex items-center gap-2 mb-2">
            <Sparkles className="w-5 h-5 text-[#facc15] animate-pulse" />
            <h4 className="text-sm font-black uppercase text-[#facc15] tracking-wider">
              Gemini AI Smart Input (Otomatis Isi Data)
            </h4>
            <span className="text-[10px] bg-[#facc15]/10 text-[#facc15] px-2 py-0.5 font-bold uppercase tracking-widest border border-[#facc15]/20">
              Feature Active
            </span>
          </div>
          <p className="text-[11px] text-slate-400 mb-3 leading-relaxed">
            Tempel CV, biodata kasar, atau pesan WhatsApp calon pegawai di bawah ini. Gemini AI akan menganalisis dan mengisi seluruh formulir secara instan dan otomatis!
          </p>
          <div className="space-y-3">
            <textarea
              rows={3}
              value={aiRawText}
              onChange={(e) => setAiRawText(e.target.value)}
              placeholder="Contoh: Nama saya Ahmad Subarjo, NIK 3273012345678901, lahir di Bandung tanggal 17 Agustus 1994. Saya baru bergabung sebagai Staff di divisi Operations mulai hari ini. No HP 081234567890, email ahmad.subarjo@example.com, alamat Jl. Merdeka No. 123, Bandung."
              className="w-full bg-black border border-[#222] focus:border-[#facc15] focus:outline-hidden text-xs font-mono p-3 text-white"
            />
            <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3">
              <div className="text-[10px] text-slate-500 font-mono">
                *Pastikan data penting seperti Nama, NIK, dan Divisi tertulis dengan jelas.
              </div>
              <button
                type="button"
                disabled={isAiParsing || !aiRawText.trim()}
                onClick={handleAiParse}
                className="w-full sm:w-auto bg-[#facc15] hover:bg-yellow-500 disabled:bg-[#222] disabled:text-[#666] text-black font-black uppercase text-xs px-4 py-2.5 flex items-center justify-center gap-2 transition-all cursor-pointer"
              >
                {isAiParsing ? (
                  <>
                    <RefreshCw className="w-4 h-4 animate-spin" />
                    Menganalisis dengan Gemini...
                  </>
                ) : (
                  <>
                    <Sparkles className="w-4 h-4" />
                    Ekstrak dengan Gemini AI
                  </>
                )}
              </button>
            </div>
            {aiParseError && (
              <p className="text-rose-400 text-[11px] font-mono uppercase mt-1">
                ⚠️ Gagal mengekstrak: {aiParseError}
              </p>
            )}
            {aiParseSuccess && (
              <p className="text-green-400 text-[11px] font-mono uppercase mt-1">
                ✅ {aiParseSuccess}
              </p>
            )}
          </div>
        </div>
      )}

      <form onSubmit={handleSubmit} className="space-y-6">
        {Object.keys(errors).length > 0 && (
          <div className="bg-rose-500/10 border border-rose-500/20 p-4 rounded-none text-rose-400 text-xs font-mono uppercase space-y-1">
            <div className="font-black text-[#facc15] mb-1 flex items-center gap-1.5">
              <ShieldAlert className="w-4.5 h-4.5 text-rose-500" />
              Ada kesalahan pengisian data (Gagal Validasi):
            </div>
            {Object.entries(errors).map(([key, msg]) => (
              <div key={key} className="flex items-center gap-2">
                <span className="text-rose-500">•</span>
                <span>{msg}</span>
              </div>
            ))}
          </div>
        )}
        
        {/* Row 1: Profile Photo and NIP/NIK details */}
        <div className="flex flex-col md:flex-row gap-6">
          <div className="flex flex-col items-center gap-3">
            <span className="text-xs font-black text-slate-400 uppercase tracking-wider">Foto Pegawai</span>
            <div className="relative w-32 h-32 rounded-none border-2 border-dashed border-[#222] flex items-center justify-center overflow-hidden bg-[#050505]">
              {photoUrl ? (
                <>
                  <img src={photoUrl} alt="Employee Preview" className="w-full h-full object-cover" />
                  <button 
                    type="button"
                    onClick={() => setPhotoUrl("")}
                    className="absolute top-1 right-1 bg-rose-600 text-white rounded-none p-1 shadow-none hover:bg-rose-700"
                  >
                    <X className="w-3.5 h-3.5" />
                  </button>
                </>
              ) : (
                <div className="text-center p-3 text-slate-500">
                  <User className="w-8 h-8 mx-auto mb-1 opacity-70" />
                  <span className="text-[10px] uppercase font-mono block">No Photo</span>
                </div>
              )}
            </div>
            <label className="cursor-pointer bg-[#111] border border-[#222] text-slate-300 text-xs px-3 py-1.5 rounded-none hover:bg-black hover:text-white hover:border-slate-500 transition-all flex items-center gap-1.5 uppercase font-black tracking-wider">
              <Upload className="w-3.5 h-3.5 text-[#facc15]" />
              Upload Foto
              <input 
                type="file"
                accept="image/*"
                onChange={handlePhotoUpload}
                className="hidden"
              />
            </label>
            {errors.photo && <span className="text-[10px] text-rose-500 font-mono uppercase">{errors.photo}</span>}
          </div>

          <div className="flex-1 grid grid-cols-1 md:grid-cols-2 gap-4">
            {/* NIP Internal Input with Real-time Duplicate Check */}
            <div>
              <div className="flex items-center justify-between mb-1">
                <label className="block text-xs font-black text-slate-400 uppercase tracking-wider flex items-center gap-1">
                  <CreditCard className="w-3.5 h-3.5 text-[#facc15]" />
                  NIP Internal
                </label>
                <button
                  type="button"
                  onClick={() => {
                    const nextState = !isCustomNipEnabled;
                    setIsCustomNipEnabled(nextState);
                    if (nextState && !customNip) {
                      setCustomNip(effectiveNip);
                    }
                  }}
                  className="text-[10px] font-mono text-[#facc15] hover:underline flex items-center gap-1 cursor-pointer"
                >
                  <Edit3 className="w-3 h-3" />
                  {isCustomNipEnabled ? "Gunakan Auto-NIP" : "Edit NIP Manual"}
                </button>
              </div>

              <input 
                type="text" 
                value={effectiveNip}
                onChange={(e) => {
                  setCustomNip(e.target.value.replace(/\D/g, ""));
                  setIsCustomNipEnabled(true);
                }}
                readOnly={!isCustomNipEnabled && !employee}
                className={`w-full font-mono text-sm rounded-none px-3 py-2 font-black transition-all ${
                  duplicateNipMatch || errors.nip
                    ? "border-2 border-rose-500 text-rose-200 bg-rose-950/30 focus:outline-none" 
                    : isCustomNipEnabled 
                    ? "bg-[#111] border border-[#facc15] text-white focus:outline-none focus:ring-1 focus:ring-[#facc15]" 
                    : "bg-[#050505] border border-[#222] text-slate-400 cursor-not-allowed"
                }`}
              />

              {/* Real-time duplicate NIP notification */}
              {duplicateNipMatch ? (
                <div className="mt-1.5 p-2 bg-rose-950/80 border border-rose-500/60 text-rose-300 text-[11px] font-mono flex items-start gap-1.5">
                  <AlertTriangle className="w-3.5 h-3.5 text-rose-400 shrink-0 mt-0.5 animate-bounce" />
                  <div>
                    <strong className="text-rose-200 font-bold block uppercase">⚠️ DUPLIKASI NIP TERDETEKSI!</strong>
                    NIP <code className="bg-black px-1 text-yellow-300 font-bold">{effectiveNip}</code> telah digunakan oleh <strong>{duplicateNipMatch.name}</strong> (Divisi {duplicateNipMatch.division}). Harap ubah NIP.
                  </div>
                </div>
              ) : errors.nip ? (
                <span className="text-[10px] text-rose-500 font-mono mt-1 block uppercase">{errors.nip}</span>
              ) : effectiveNip ? (
                <div className="text-[10px] text-emerald-400 font-mono mt-1 flex items-center gap-1 font-bold">
                  <CheckCircle2 className="w-3 h-3 text-emerald-400" />
                  <span>NIP Unik & Sistem Terverifikasi</span>
                </div>
              ) : (
                <p className="text-[9px] text-slate-500 font-mono mt-1 uppercase">Dihasilkan dari birthYear + joinYear + index urut.</p>
              )}
            </div>

            {/* NIK KTP Input with Real-time Duplicate Check */}
            <div>
              <div className="flex items-center justify-between mb-1">
                <label className="block text-xs font-black text-slate-400 uppercase tracking-wider">
                  NIK KTP (Pemerintah) <span className="text-rose-500">*</span>
                </label>
                {nik.trim() && !duplicateNikMatch && /^\d{8,20}$/.test(nik.trim()) && (
                  <span className="text-[10px] text-emerald-400 font-mono flex items-center gap-1 font-bold">
                    <CheckCircle2 className="w-3 h-3 text-emerald-400" /> NIK Unik
                  </span>
                )}
              </div>

              <input 
                type="text" 
                maxLength={20}
                value={nik}
                onChange={(e) => setNik(e.target.value.replace(/\D/g, ""))}
                placeholder="3273xxxxxxxxxxxx"
                className={`w-full font-mono rounded-none px-3 py-2 text-sm transition-all ${
                  duplicateNikMatch || errors.nik
                    ? 'bg-rose-950/30 border-2 border-rose-500 text-rose-200 focus:outline-none' 
                    : 'bg-[#111] border border-[#222] text-white focus:outline-none focus:border-[#facc15]'
                }`}
              />

              {/* Real-time duplicate NIK notification */}
              {duplicateNikMatch ? (
                <div className="mt-1.5 p-2 bg-rose-950/80 border border-rose-500/60 text-rose-300 text-[11px] font-mono flex items-start gap-1.5">
                  <AlertTriangle className="w-3.5 h-3.5 text-rose-400 shrink-0 mt-0.5 animate-bounce" />
                  <div>
                    <strong className="text-rose-200 font-bold block uppercase">⚠️ DUPLIKASI NIK TERDETEKSI!</strong>
                    NIK <code className="bg-black px-1 text-yellow-300 font-bold">{nik}</code> sudah terdaftar pada pegawai: <strong className="text-white">{duplicateNikMatch.name}</strong> ({duplicateNikMatch.position} — Divisi {duplicateNikMatch.division}).
                  </div>
                </div>
              ) : errors.nik ? (
                <span className="text-[10px] text-rose-500 font-mono mt-1 block uppercase">{errors.nik}</span>
              ) : nik.trim() ? (
                <span className="text-[10px] text-slate-500 font-mono mt-1 block">Panjang: {nik.length} Digit (KTP Valid: 16 Digit)</span>
              ) : null}
            </div>

            <div className="md:col-span-2">
              <label className="block text-xs font-black text-slate-400 uppercase tracking-wider mb-1">
                Nama Lengkap Sesuai KTP <span className="text-rose-500">*</span>
              </label>
              <input 
                type="text" 
                value={name}
                onChange={(e) => setName(e.target.value)}
                placeholder="Masukkan nama lengkap"
                className={`w-full bg-[#111] border text-white font-mono rounded-none px-3 py-2 text-sm focus:outline-hidden focus:border-[#facc15] ${errors.name ? 'border-rose-500' : 'border-[#222]'}`}
              />
              {errors.name && <span className="text-[10px] text-rose-500 font-mono mt-1 block uppercase">{errors.name}</span>}
            </div>
          </div>
        </div>

        <hr className="border-[#111]" />

        {/* Row 2: Demographics */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div>
            <label className="block text-xs font-black text-slate-400 uppercase tracking-wider mb-1">
              Gender <span className="text-rose-500">*</span>
            </label>
            <div className="flex gap-4">
              <label className="inline-flex items-center gap-1.5 text-sm cursor-pointer mt-1 font-mono uppercase text-slate-300">
                <input 
                  type="radio" 
                  name="gender" 
                  value="L" 
                  checked={gender === "L"} 
                  onChange={() => setGender("L")}
                  className="accent-[#facc15]"
                />
                Laki-laki
              </label>
              <label className="inline-flex items-center gap-1.5 text-sm cursor-pointer mt-1 font-mono uppercase text-slate-300">
                <input 
                  type="radio" 
                  name="gender" 
                  value="P" 
                  checked={gender === "P"} 
                  onChange={() => setGender("P")}
                  className="accent-[#facc15]"
                />
                Perempuan
              </label>
            </div>
          </div>

          <div>
            <label className="block text-xs font-black text-slate-400 uppercase tracking-wider mb-1">
              Tempat Lahir <span className="text-rose-500">*</span>
            </label>
            <input 
              type="text" 
              value={birthPlace}
              onChange={(e) => setBirthPlace(e.target.value)}
              placeholder="Kota lahir"
              className={`w-full bg-[#111] border text-white font-mono rounded-none px-3 py-2 text-sm focus:outline-hidden focus:border-[#facc15] ${errors.birthPlace ? 'border-rose-500' : 'border-[#222]'}`}
            />
            {errors.birthPlace && <span className="text-[10px] text-rose-500 font-mono mt-1 block uppercase">{errors.birthPlace}</span>}
          </div>

          <div>
            <label className="block text-xs font-black text-slate-400 uppercase tracking-wider mb-1">
              Tanggal Lahir <span className="text-rose-500">*</span>
            </label>
            <input 
              type="date" 
              value={birthDate}
              onChange={(e) => setBirthDate(e.target.value)}
              className="w-full bg-[#111] border border-[#222] text-white font-mono rounded-none px-3 py-2 text-sm focus:outline-hidden focus:border-[#facc15]"
            />
            <div className="text-[10px] text-[#facc15] font-black uppercase mt-1.5 flex items-center gap-1 font-mono">
              <Calendar className="w-3 h-3" />
              Auto Umur: {autoAge} Tahun
            </div>
          </div>
        </div>

        <hr className="border-[#111]" />

        {/* Row 3: Corporate Placement */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div>
            <label className="block text-xs font-black text-slate-400 uppercase tracking-wider mb-1">
              TMT Kerja (Join Date) <span className="text-rose-500">*</span>
            </label>
            <input 
              type="date" 
              value={tmtKerja}
              onChange={(e) => setTmtKerja(e.target.value)}
              className="w-full bg-[#111] border border-[#222] text-white font-mono rounded-none px-3 py-2 text-sm focus:outline-hidden focus:border-[#facc15]"
            />
            <div className="text-[10px] text-[#facc15] font-black uppercase mt-1.5 flex items-center gap-1 font-mono">
              <Calendar className="w-3 h-3" />
              Masa Kerja: {autoTenure.text}
            </div>
          </div>

          <div>
            <label className="block text-xs font-black text-slate-400 uppercase tracking-wider mb-1">
              Divisi Perusahaan <span className="text-rose-500">*</span>
            </label>
            <select 
              value={division}
              onChange={(e) => setDivision(e.target.value)}
              className="w-full bg-[#111] border border-[#222] text-white font-mono rounded-none px-3 py-2 text-sm focus:outline-hidden focus:border-[#facc15]"
            >
              {DIVISION_LIST.map((div, i) => (
                <option key={i} value={div}>{div}</option>
              ))}
            </select>
          </div>

          <div>
            <label className="block text-xs font-black text-slate-400 uppercase tracking-wider mb-1">
              Jabatan Resmi <span className="text-rose-500">*</span>
            </label>
            <select 
              value={position}
              onChange={(e) => setPosition(e.target.value)}
              className="w-full bg-[#111] border border-[#222] text-white font-mono rounded-none px-3 py-2 text-sm focus:outline-hidden focus:border-[#facc15]"
            >
              {POSITION_LIST.map((pos, i) => (
                <option key={i} value={pos}>{pos}</option>
              ))}
            </select>
          </div>
        </div>

        {/* Row 4: Reporting & Status */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div>
            <label className="block text-xs font-black text-slate-400 uppercase tracking-wider mb-1">
              Atasan Langsung (Reporting To)
            </label>
            <select 
              value={reportingTo}
              onChange={(e) => setReportingTo(e.target.value)}
              className="w-full bg-[#111] border border-[#222] text-white font-mono rounded-none px-3 py-2 text-sm focus:outline-hidden focus:border-[#facc15]"
            >
              <option value="none">Tidak Ada (Top Level)</option>
              {supervisorsList.map((sup) => (
                <option key={sup.id} value={sup.id}>
                  {sup.name} ({sup.position} — {sup.division})
                </option>
              ))}
            </select>
            <p className="text-[9px] text-slate-500 font-mono mt-1 uppercase">Mengikat persetujuan workflow berjenjang.</p>
          </div>

          <div>
            <label className="block text-xs font-black text-slate-400 uppercase tracking-wider mb-1">
              Status Pegawai <span className="text-rose-500">*</span>
            </label>
            <select 
              value={status}
              onChange={(e) => setStatus(e.target.value as Employee["status"])}
              className="w-full bg-[#111] border border-[#222] text-white font-mono rounded-none px-3 py-2 text-sm focus:outline-hidden focus:border-[#facc15]"
            >
              <option value="Aktif">Karyawan Tetap (Aktif)</option>
              <option value="Kontrak">Kontrak (PKWT)</option>
              <option value="Pensiun">Pensiun</option>
              <option value="Resigned">Resigned / Keluar</option>
            </select>
          </div>

          <div>
            <label className="block text-xs font-black text-slate-400 uppercase tracking-wider mb-1">
              Skor KPI Awal (0-100)
            </label>
            <input 
              type="number" 
              min={0} 
              max={100}
              value={kpiScore}
              onChange={(e) => setKpiScore(Math.min(100, Math.max(0, Number(e.target.value))))}
              className="w-full bg-[#111] border border-[#222] text-white font-mono rounded-none px-3 py-2 text-sm focus:outline-hidden focus:border-[#facc15]"
            />
          </div>
        </div>

        <hr className="border-[#111]" />

        {/* Row 5: Contact Details */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <label className="block text-xs font-black text-slate-400 uppercase tracking-wider mb-1">
              Nomor Handphone (HP)
            </label>
            <input 
              type="text" 
              value={phone}
              onChange={(e) => setPhone(e.target.value)}
              placeholder="08xxxxxxxxxx"
              className={`w-full bg-[#111] border text-white font-mono rounded-none px-3 py-2 text-sm focus:outline-hidden focus:border-[#facc15] ${errors.phone ? 'border-rose-500' : 'border-[#222]'}`}
            />
            {errors.phone && <span className="text-[10px] text-rose-500 font-mono mt-1 block uppercase">{errors.phone}</span>}
          </div>

          <div>
            <label className="block text-xs font-black text-slate-400 uppercase tracking-wider mb-1">
              Email Pribadi / Kantor
            </label>
            <input 
              type="text" 
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder="pegawai@emsgan.com"
              className={`w-full bg-[#111] border text-white font-mono rounded-none px-3 py-2 text-sm focus:outline-hidden focus:border-[#facc15] ${errors.email ? 'border-rose-500' : 'border-[#222]'}`}
            />
            {errors.email && <span className="text-[10px] text-rose-500 font-mono mt-1 block uppercase">{errors.email}</span>}
          </div>

          <div className="md:col-span-2">
            <label className="block text-xs font-black text-slate-400 uppercase tracking-wider mb-1">
              Alamat Lengkap Sesuai KTP
            </label>
            <textarea 
              rows={2}
              value={address}
              onChange={(e) => setAddress(e.target.value)}
              placeholder="Jl. Raya No. X, Kel, Kec..."
              className="w-full bg-[#111] border border-[#222] text-white font-mono rounded-none px-3 py-2 text-sm focus:outline-hidden focus:border-[#facc15]"
            />
          </div>
        </div>

        {/* Submit Actions */}
        <div className="flex items-center justify-end gap-3 pt-4 border-t border-[#222]">
          <button 
            type="button"
            onClick={onCancel}
            className="border border-[#222] text-slate-300 px-4 py-2 rounded-none text-xs font-black uppercase tracking-wider hover:bg-[#111] transition-colors"
          >
            Batal
          </button>
          <button 
            type="submit"
            className="bg-[#facc15] hover:bg-yellow-500 text-black px-5 py-2 rounded-none text-xs font-black uppercase tracking-wider transition-colors flex items-center gap-2"
          >
            <Save className="w-4 h-4" />
            Simpan Data Pegawai
          </button>
        </div>
      </form>
    </div>
  );
}
