import React, { useState, useEffect } from "react";
import { supabaseService, SupabaseStatus } from "../services/supabaseService";
import { Employee } from "../types";
import { Database, CheckCircle2, AlertTriangle, RefreshCw, Copy, Check, Server, ExternalLink, Key, Zap, ShieldCheck } from "lucide-react";

interface SupabaseModalProps {
  isOpen: boolean;
  onClose: () => void;
  employees: Employee[];
  onSyncCompleted?: (count: number) => void;
}

export const SupabaseModal: React.FC<SupabaseModalProps> = ({
  isOpen,
  onClose,
  employees,
  onSyncCompleted
}) => {
  const [supabaseUrl, setSupabaseUrl] = useState<string>("");
  const [supabaseKey, setSupabaseKey] = useState<string>("");
  const [status, setStatus] = useState<SupabaseStatus>({
    connected: false,
    message: "Memeriksa status koneksi Supabase..."
  });
  const [isTesting, setIsTesting] = useState<boolean>(false);
  const [isSyncing, setIsSyncing] = useState<boolean>(false);
  const [copiedSql, setCopiedSql] = useState<boolean>(false);
  const [syncMessage, setSyncMessage] = useState<string | null>(null);

  useEffect(() => {
    if (isOpen) {
      const storedUrl = localStorage.getItem("supabase_url") || "";
      const storedKey = localStorage.getItem("supabase_key") || "";
      setSupabaseUrl(storedUrl);
      setSupabaseKey(storedKey);

      if (storedUrl && storedKey) {
        supabaseService.configure(storedUrl, storedKey);
      }
      checkStatus();
    }
  }, [isOpen]);

  const checkStatus = async () => {
    setIsTesting(true);
    const res = await supabaseService.checkConnection();
    setStatus(res);
    setIsTesting(false);
  };

  const handleSaveConfig = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!supabaseUrl || !supabaseKey) return;

    localStorage.setItem("supabase_url", supabaseUrl);
    localStorage.setItem("supabase_key", supabaseKey);
    supabaseService.configure(supabaseUrl, supabaseKey);

    setIsTesting(true);
    const res = await supabaseService.checkConnection();
    setStatus(res);
    setIsTesting(false);
  };

  const handleSyncData = async () => {
    setIsSyncing(true);
    setSyncMessage(null);
    const result = await supabaseService.syncEmployees(employees);
    setIsSyncing(false);

    if (result.success) {
      setSyncMessage(`Berhasil menyinkronkan ${result.count || employees.length} data pegawai ke Supabase!`);
      if (onSyncCompleted) onSyncCompleted(result.count || employees.length);
    } else {
      setSyncMessage(`Gagal menyinkronkan: ${result.error || 'Terjadi kesalahan'}`);
    }
  };

  const handleCopySql = () => {
    const sql = supabaseService.getTableSchemaSql();
    navigator.clipboard.writeText(sql);
    setCopiedSql(true);
    setTimeout(() => setCopiedSql(false), 2500);
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-[#00000080] inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm animate-fadeIn">
      <div className="bg-[#0c0c0c] border border-[#222] rounded-none w-full max-w-2xl overflow-hidden shadow-2xl space-y-0">
        
        {/* Header */}
        <div className="bg-[#111] px-6 py-4 border-b border-[#222] flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div className="p-2 bg-emerald-500/10 border border-emerald-500/30 text-emerald-400">
              <Database className="w-5 h-5" />
            </div>
            <div>
              <h3 className="text-sm font-black text-white uppercase tracking-wider flex items-center gap-2">
                Integrasi Database Supabase (PostgreSQL Cloud)
              </h3>
              <p className="text-[11px] text-slate-400 font-mono">
                Sinkronkan seluruh data pegawai, dokumen DMS, & audit logs ke Supabase
              </p>
            </div>
          </div>
          <button
            onClick={onClose}
            className="text-slate-400 hover:text-white text-sm font-mono font-bold px-2 py-1 bg-[#1a1a1a] border border-[#333]"
          >
            ✕
          </button>
        </div>

        {/* Content Body */}
        <div className="p-6 space-y-6 max-h-[80vh] overflow-y-auto font-mono">
          
          {/* Status Indicator Banner */}
          <div className={`p-4 border flex items-start gap-3.5 ${
            status.connected 
              ? "bg-emerald-500/10 border-emerald-500/40 text-emerald-300"
              : "bg-amber-500/10 border-amber-500/40 text-amber-300"
          }`}>
            {status.connected ? (
              <CheckCircle2 className="w-5 h-5 text-emerald-400 shrink-0 mt-0.5" />
            ) : (
              <AlertTriangle className="w-5 h-5 text-amber-400 shrink-0 mt-0.5" />
            )}
            <div className="space-y-1 flex-1">
              <div className="flex items-center justify-between">
                <h4 className="text-xs font-black uppercase tracking-wider">
                  STATUS KONEKSI: {status.connected ? "TERHUBUNG (ONLINE)" : "TERDISKONIKASI / DEMO MODE"}
                </h4>
                <button
                  onClick={checkStatus}
                  disabled={isTesting}
                  className="text-[10px] bg-[#151515] hover:bg-[#222] text-slate-200 border border-[#333] px-2 py-0.5 flex items-center gap-1 uppercase"
                >
                  <RefreshCw className={`w-3 h-3 ${isTesting ? 'animate-spin text-emerald-400' : ''}`} />
                  Cek Ulang
                </button>
              </div>
              <p className="text-[11px] text-slate-300 leading-relaxed">{status.message}</p>
            </div>
          </div>

          {/* Quick Actions & Sync Section */}
          <div className="bg-[#111] border border-[#222] p-4 space-y-3">
            <div className="flex items-center justify-between">
              <div>
                <h5 className="text-xs font-bold text-white uppercase tracking-wider flex items-center gap-2">
                  <Zap className="w-4 h-4 text-emerald-400" /> Sinkronisasi Data Pegawai ({employees.length} Record)
                </h5>
                <p className="text-[10px] text-slate-400 mt-0.5">
                  Proses ekspor/pembaruan instan seluruh tabel data pegawai ke Supabase PostgreSQL.
                </p>
              </div>
              <button
                onClick={handleSyncData}
                disabled={isSyncing}
                className="bg-emerald-600 hover:bg-emerald-500 disabled:opacity-50 text-white font-black text-xs px-4 py-2.5 flex items-center gap-2 uppercase tracking-wider transition-colors border border-emerald-400/40 shrink-0"
              >
                {isSyncing ? (
                  <>
                    <RefreshCw className="w-4 h-4 animate-spin" />
                    Menyinkronkan...
                  </>
                ) : (
                  <>
                    <Database className="w-4 h-4" />
                    Sync ke Supabase
                  </>
                )}
              </button>
            </div>

            {syncMessage && (
              <div className="p-2.5 bg-[#000] border border-[#333] text-[11px] font-mono text-emerald-400">
                {syncMessage}
              </div>
            )}
          </div>

          {/* Configuration Form */}
          <form onSubmit={handleSaveConfig} className="bg-[#111] border border-[#222] p-4 space-y-4">
            <h5 className="text-xs font-bold text-white uppercase tracking-wider flex items-center gap-2 border-b border-[#222] pb-2">
              <Key className="w-4 h-4 text-yellow-400" /> Pengaturan API Key Supabase (Supabase Project API)
            </h5>

            <div className="space-y-3 text-xs">
              <div>
                <label className="block text-[11px] font-bold text-slate-300 uppercase mb-1">
                  Supabase Project URL (VITE_SUPABASE_URL)
                </label>
                <input
                  type="url"
                  placeholder="https://xyzcompany.supabase.co"
                  value={supabaseUrl}
                  onChange={(e) => setSupabaseUrl(e.target.value)}
                  className="w-full bg-[#050505] border border-[#333] focus:border-emerald-500 text-white px-3 py-2 text-xs font-mono outline-none"
                />
              </div>

              <div>
                <label className="block text-[11px] font-bold text-slate-300 uppercase mb-1">
                  Supabase Anon Public Key (VITE_SUPABASE_ANON_KEY)
                </label>
                <input
                  type="password"
                  placeholder="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
                  value={supabaseKey}
                  onChange={(e) => setSupabaseKey(e.target.value)}
                  className="w-full bg-[#050505] border border-[#333] focus:border-emerald-500 text-white px-3 py-2 text-xs font-mono outline-none"
                />
              </div>
            </div>

            <div className="flex items-center justify-between pt-2">
              <span className="text-[10px] text-slate-500 italic">
                Kredensial disimpan secara terenkripsi di local session browser.
              </span>
              <button
                type="submit"
                className="bg-[#222] hover:bg-[#333] text-white font-bold text-xs px-4 py-2 border border-[#444] uppercase tracking-wider"
              >
                Simpan & Hubungkan
              </button>
            </div>
          </form>

          {/* Schema DDL Exporter */}
          <div className="bg-[#111] border border-[#222] p-4 space-y-3">
            <div className="flex items-center justify-between">
              <div>
                <h5 className="text-xs font-bold text-white uppercase tracking-wider flex items-center gap-2">
                  <Server className="w-4 h-4 text-cyan-400" /> Skema Tabel Database (SQL DDL)
                </h5>
                <p className="text-[10px] text-slate-400 mt-0.5">
                  Jalankan SQL DDL ini di menu Supabase Dashboard SQL Editor untuk membuat tabel secara otomatis.
                </p>
              </div>
              <button
                onClick={handleCopySql}
                className="bg-[#1a1a1a] hover:bg-[#252525] text-slate-200 font-bold text-xs px-3 py-1.5 border border-[#333] flex items-center gap-1.5 uppercase transition-colors"
              >
                {copiedSql ? (
                  <>
                    <Check className="w-3.5 h-3.5 text-emerald-400" />
                    Tersalin!
                  </>
                ) : (
                  <>
                    <Copy className="w-3.5 h-3.5" />
                    Salin SQL DDL
                  </>
                )}
              </button>
            </div>

            <pre className="p-3 bg-[#050505] border border-[#222] text-[10px] text-slate-300 font-mono overflow-x-auto max-h-36 selection:bg-emerald-500/30">
              {supabaseService.getTableSchemaSql()}
            </pre>
          </div>

        </div>

        {/* Footer */}
        <div className="bg-[#111] px-6 py-3 border-t border-[#222] flex items-center justify-between text-xs font-mono">
          <a
            href="https://supabase.com/dashboard"
            target="_blank"
            rel="noopener noreferrer"
            className="text-slate-400 hover:text-emerald-400 flex items-center gap-1 text-[11px]"
          >
            <span>Buka Supabase Dashboard</span>
            <ExternalLink className="w-3 h-3" />
          </a>
          <button
            onClick={onClose}
            className="bg-[#222] hover:bg-[#333] text-white font-bold px-4 py-1.5 uppercase tracking-wider border border-[#444]"
          >
            Tutup
          </button>
        </div>

      </div>
    </div>
  );
};

export default SupabaseModal;
