import React, { useState, useEffect } from 'react';
import { Database, RefreshCw, CheckCircle2, AlertTriangle, HardDrive, Server, ShieldCheck, X } from 'lucide-react';
import Swal from 'sweetalert2';
import { useStore } from '../context/StoreContext';

interface DbStatusResponse {
  isMysqlActive: boolean;
  storageEngine: string;
  lastMysqlError: string | null;
  config: {
    host: string | null;
    user: string | null;
    database: string | null;
    port: number;
    isConfigured: boolean;
  };
}

interface Props {
  isOpen: boolean;
  onClose: () => void;
}

export const DatabaseStatusModal: React.FC<Props> = ({ isOpen, onClose }) => {
  const { exportDatabaseToJson, db } = useStore();
  const [status, setStatus] = useState<DbStatusResponse | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [isTesting, setIsTesting] = useState(false);

  const safeJsonParse = async (response: Response) => {
    try {
      const text = await response.text();
      try {
        return JSON.parse(text);
      } catch (_e) {
        return {
          success: false,
          isMysqlActive: false,
          lastMysqlError: text.slice(0, 200) || 'Server mengembalikan respon bukan format JSON.',
          message: text.slice(0, 200) || 'Server mengembalikan respon bukan format JSON.'
        };
      }
    } catch (e: any) {
      return {
        success: false,
        isMysqlActive: false,
        lastMysqlError: e.message,
        message: e.message
      };
    }
  };

  const fetchStatus = async () => {
    setIsLoading(true);
    try {
      const res = await fetch('/api/db/status');
      const data = await safeJsonParse(res);
      setStatus(data);
    } catch (e) {
      console.error('Failed to fetch DB status:', e);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    if (isOpen) {
      fetchStatus();
    }
  }, [isOpen]);

  const handleTestReconnect = async () => {
    setIsTesting(true);
    try {
      const res = await fetch('/api/db/reconnect', { method: 'POST' });
      const data = await safeJsonParse(res);
      await fetchStatus();

      if (data.success || data.isMysqlActive) {
        Swal.fire({
          icon: 'success',
          title: 'Terhubung ke MySQL!',
          text: data.message || 'Database MySQL berhasil terhubung dari file .env.',
          timer: 3000,
          showConfirmButton: false
        });
      } else {
        Swal.fire({
          icon: 'warning',
          title: 'Koneksi MySQL Belum Berhasil',
          html: `<div class="text-left text-xs space-y-2">
            <p><strong>Pesan dari Server Node.js:</strong></p>
            <p class="font-mono bg-slate-100 p-2 rounded text-slate-800 break-all">${data.lastMysqlError || data.message || 'Koneksi ditolak'}</p>
            <hr/>
            <p class="text-slate-600">Pastikan parameter di file <code>.env</code> sudah sesuai dengan host/user database MySQL Anda.</p>
          </div>`,
          confirmButtonText: 'Tutup'
        });
      }
    } catch (e: any) {
      Swal.fire({
        icon: 'error',
        title: 'Gagal Menghubungi Server',
        text: e.message || 'Periksa koneksi jaringan server.'
      });
    } finally {
      setIsTesting(false);
    }
  };

  if (!isOpen) return null;

  const isMysql = status?.isMysqlActive;
  const isConfigured = status?.config?.isConfigured;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-3 sm:p-4 bg-slate-900/60 backdrop-blur-xs animate-in fade-in">
      <div className="bg-white rounded-2xl shadow-2xl border border-slate-200 w-full max-w-2xl overflow-hidden flex flex-col max-h-[92vh]">
        {/* Header */}
        <div className="flex items-center justify-between px-5 sm:px-6 py-4 border-b border-slate-100 bg-slate-50/80">
          <div className="flex items-center space-x-3">
            <div className={`p-2.5 rounded-xl ${isMysql ? 'bg-emerald-100 text-emerald-700' : 'bg-blue-100 text-blue-700'}`}>
              <Database className="w-5 h-5" />
            </div>
            <div>
              <h2 className="text-base sm:text-lg font-bold text-slate-800">Status Database & Server</h2>
              <p className="text-xs text-slate-500">Informasi pembacaan file .env dan status koneksi database</p>
            </div>
          </div>
          <button
            onClick={onClose}
            className="p-2 text-slate-400 hover:text-slate-600 hover:bg-slate-100 rounded-lg transition-colors"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Content */}
        <div className="p-5 sm:p-6 overflow-y-auto space-y-5">
          {/* Storage Engine Status Banner */}
          <div className={`p-4 rounded-xl border flex items-start space-x-3.5 ${isMysql
              ? 'bg-emerald-50 border-emerald-200 text-emerald-900'
              : 'bg-amber-50 border-amber-200 text-amber-900'
            }`}>
            <div className={`p-2 rounded-lg mt-0.5 shrink-0 ${isMysql ? 'bg-emerald-100 text-emerald-700' : 'bg-amber-100 text-amber-700'}`}>
              {isMysql ? <CheckCircle2 className="w-5 h-5" /> : <HardDrive className="w-5 h-5" />}
            </div>
            <div className="flex-1 min-w-0">
              <div className="flex items-center justify-between gap-2">
                <h3 className="font-bold text-sm sm:text-base">
                  {isMysql ? 'MySQL Database (Aktif & Terhubung)' : 'Menunggu Koneksi MySQL (.env)'}
                </h3>
                <span className={`text-[11px] px-2.5 py-0.5 rounded-full font-bold shrink-0 ${isMysql ? 'bg-emerald-200 text-emerald-800' : 'bg-amber-200 text-amber-800'
                  }`}>
                  {isMysql ? 'MySQL Online' : 'Belum Terhubung'}
                </span>
              </div>
              <p className="text-xs mt-1 text-slate-600 leading-relaxed">
                {isMysql
                  ? 'Server Node.js telah membaca file .env dan berhasil tersambung ke database MySQL. Seluruh transaksi dan data produk tersimpan langsung di tabel database.'
                  : 'Server Node.js membaca kredensial dari file .env. Pastikan MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD, dan MYSQL_DATABASE sudah diisi pada file .env.'}
              </p>
            </div>
          </div>

          {/* MySQL Configuration Read by Server */}
          <div className="border border-slate-200 rounded-xl overflow-hidden">
            <div className="px-4 py-3 bg-slate-50 border-b border-slate-200 flex items-center justify-between">
              <div className="flex items-center space-x-2">
                <Server className="w-4 h-4 text-slate-600" />
                <span className="font-bold text-xs sm:text-sm text-slate-700">Parameter yang Dibaca dari .env</span>
              </div>
              <button
                type="button"
                onClick={fetchStatus}
                disabled={isLoading}
                className="text-xs text-slate-600 hover:text-slate-900 flex items-center space-x-1 py-1 px-2.5 rounded-md hover:bg-slate-200/60 transition"
              >
                <RefreshCw className={`w-3.5 h-3.5 ${isLoading ? 'animate-spin' : ''}`} />
                <span>Segarkan</span>
              </button>
            </div>

            <div className="p-4 space-y-3 text-xs">
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-2.5">
                <div className="p-2.5 bg-slate-50 rounded-lg border border-slate-100">
                  <span className="text-slate-500 block text-[11px]">MYSQL_HOST:</span>
                  <span className="font-mono font-medium text-slate-800">
                    {status?.config?.host || <span className="text-amber-600 italic">Belum diisi</span>}
                  </span>
                </div>

                <div className="p-2.5 bg-slate-50 rounded-lg border border-slate-100">
                  <span className="text-slate-500 block text-[11px]">MYSQL_PORT:</span>
                  <span className="font-mono font-medium text-slate-800">{status?.config?.port || 3306}</span>
                </div>

                <div className="p-2.5 bg-slate-50 rounded-lg border border-slate-100">
                  <span className="text-slate-500 block text-[11px]">MYSQL_DATABASE:</span>
                  <span className="font-mono font-medium text-slate-800">
                    {status?.config?.database || <span className="text-amber-600 italic">Belum diisi</span>}
                  </span>
                </div>

                <div className="p-2.5 bg-slate-50 rounded-lg border border-slate-100">
                  <span className="text-slate-500 block text-[11px]">MYSQL_USER:</span>
                  <span className="font-mono font-medium text-slate-800">
                    {status?.config?.user || <span className="text-amber-600 italic">Belum diisi</span>}
                  </span>
                </div>
              </div>

              {status?.lastMysqlError && (
                <div className="p-3 bg-amber-50 border border-amber-200 rounded-lg flex items-start space-x-2 text-amber-800">
                  <AlertTriangle className="w-4 h-4 text-amber-600 mt-0.5 shrink-0" />
                  <div className="space-y-1">
                    <p className="font-semibold">Log Respon Server:</p>
                    <p className="font-mono text-[11px] break-all">{status.lastMysqlError}</p>
                  </div>
                </div>
              )}
            </div>

            <div className="p-3 bg-slate-50/80 border-t border-slate-100 flex items-center justify-between">
              <span className="text-xs text-slate-500">
                {isConfigured ? 'File .env terdeteksi di server' : 'Konfigurasi belum lengkap di .env'}
              </span>
              <button
                type="button"
                onClick={handleTestReconnect}
                disabled={isTesting}
                className="px-3.5 py-1.5 bg-emerald-600 hover:bg-emerald-700 text-white rounded-lg text-xs font-semibold flex items-center space-x-1.5 shadow-xs disabled:opacity-50 transition"
              >
                <RefreshCw className={`w-3.5 h-3.5 ${isTesting ? 'animate-spin' : ''}`} />
                <span>{isTesting ? 'Memeriksa...' : 'Uji Koneksi Ulang dari .env'}</span>
              </button>
            </div>
          </div>

          {/* Local Backup & Data Health */}
          <div className="p-4 bg-slate-50 rounded-xl border border-slate-200 space-y-3">
            <div className="flex items-center justify-between">
              <div className="flex items-center space-x-2">
                <ShieldCheck className="w-4 h-4 text-emerald-600" />
                <span className="font-semibold text-xs text-slate-700">Ringkasan Data Saat Ini</span>
              </div>
              <span className="text-[11px] text-slate-500">Versi {db.version || '1.0.0'}</span>
            </div>

            <div className="grid grid-cols-3 gap-2 text-center text-xs">
              <div className="p-2 bg-white rounded-lg border border-slate-100">
                <span className="text-slate-400 block text-[10px]">Total Produk</span>
                <span className="font-bold text-slate-800 text-sm">{db.products?.length || 0}</span>
              </div>
              <div className="p-2 bg-white rounded-lg border border-slate-100">
                <span className="text-slate-400 block text-[10px]">Transaksi</span>
                <span className="font-bold text-slate-800 text-sm">{db.transactions?.length || 0}</span>
              </div>
              <div className="p-2 bg-white rounded-lg border border-slate-100">
                <span className="text-slate-400 block text-[10px]">Stok Masuk/Keluar</span>
                <span className="font-bold text-slate-800 text-sm">
                  {(db.inboundRecords?.length || 0) + (db.outboundRecords?.length || 0)}
                </span>
              </div>
            </div>

            <div className="flex justify-end pt-1">
              <button
                type="button"
                onClick={exportDatabaseToJson}
                className="text-xs font-semibold text-emerald-700 hover:text-emerald-800 hover:underline flex items-center space-x-1"
              >
                <span>Unduh Cadangan Lengkap (JSON)</span>
              </button>
            </div>
          </div>
        </div>

        {/* Footer */}
        <div className="px-5 sm:px-6 py-3 bg-slate-50 border-t border-slate-100 flex justify-end">
          <button
            type="button"
            onClick={onClose}
            className="px-5 py-2 bg-slate-800 hover:bg-slate-900 text-white rounded-xl text-xs font-semibold transition-colors"
          >
            Tutup
          </button>
        </div>
      </div>
    </div>
  );
};
