import React, { useState, useEffect } from 'react';
import { useForm, usePage } from '@inertiajs/react';
// Icons
import { GiBattleship } from "react-icons/gi";
import { LuShipWheel } from "react-icons/lu";
import { HiEye, HiEyeOff } from "react-icons/hi";
// Component Alert
import { FailedAlert } from '@/components/micro/alert';

export default function Welcome() {
  const [passShow, setPassShow] = useState(false);
  const [alert, setAlert] = useState<{ title: string; desc: string } | null>(null);

  // Ambil flash messages dari shared Inertia props
  const { flash } = usePage<any>().props;

  const { data, setData, post, processing, errors } = useForm({
    username: '',
    password: '',
    remember: false,
  });

  // Otomatis tangkap flash error jika user di-redirect dari middleware/halaman lain
  useEffect(() => {
    if (flash?.error) {
      setAlert({
        title: 'Akses Ditolak',
        desc: flash.error,
      });
    }
  }, [flash]);

  const handleLogin = (e: React.FormEvent) => {
    e.preventDefault();
    
    post('/login', {
      onStart: () => setAlert(null),
      onError: (err) => {
        // Ambil pesan error validasi utama jika ada
        const firstError = err.username || err.password || 'Username atau password yang Anda masukkan tidak sesuai.';
        setAlert({
          title: 'Gagal Masuk',
          desc: firstError,
        });
      },
    });
  };

  return (
    <div className="relative min-h-screen w-full bg-slate-50 flex items-center justify-center p-4 md:p-8 overflow-hidden font-sans">
      {/* Floating Ocean Elements Background */}
      <div className="absolute inset-0 pointer-events-none overflow-hidden">
        {/* Icon 1 */}
        <div className="absolute top-[12%] right-[8%] w-16 h-16 border border-blue-200/80 rounded-2xl rotate-12 backdrop-blur-sm bg-white/60 shadow-lg shadow-blue-500/5 flex items-center justify-center text-blue-600 animate-[bounce_8s_infinite]">
          <GiBattleship size={40} />
        </div>

        {/* Icon 2 */}
        <div className="absolute bottom-[18%] left-[6%] w-20 h-20 border border-blue-200/80 rounded-full -rotate-45 backdrop-blur-sm bg-white/60 shadow-lg shadow-blue-500/5 flex items-center justify-center text-blue-500/80 animate-[bounce_10s_infinite_1s]">
          <LuShipWheel size={40} />
        </div>
      </div>

      {/* Main Container / Glassmorphism Panel Mode Terang */}
      <div className="relative z-10 w-full max-w-4xl bg-white/90 border border-slate-200/80 rounded-2xl shadow-2xl shadow-blue-900/10 backdrop-blur-xl grid grid-cols-1 md:grid-cols-12 overflow-hidden">
        
        {/* Sisi Kiri: Branding PT Alredho Teknik (Biru Laut) */}
        <div className="md:col-span-5 p-8 md:p-10 bg-linear-to-br from-blue-700 via-blue-800 to-slate-900 border-b md:border-b-0 md:border-r border-blue-800/40 flex flex-col justify-between text-white">
          <div>
            <h1 className="text-2xl md:text-3xl font-extrabold tracking-tight leading-snug">
              PT ALREDHO TEKNIK
            </h1>
            <p className="mt-3 text-sm text-blue-100/90 leading-relaxed">
              Sistem Informasi Manajemen Internal (SIM-I) yang menyatukan seluruh proses secara digital dengan berbagai modul operasional.
            </p>
          </div>

          <div className="mt-8 pt-6 border-t border-blue-500/30 text-xs text-blue-200/70 flex items-center justify-between">
            <span>&copy; 2026 PT Alredho Teknik</span>
            <span className="text-blue-300/60 font-medium">v1.0.0</span>
          </div>
        </div>

        {/* Sisi Kanan: Form Login (Terang) */}
        <div className="md:col-span-7 p-8 md:p-10 flex flex-col justify-center bg-white">
          <div className="mb-6">
            <h2 className="text-xl font-bold text-slate-800 tracking-tight">Masuk ke Akun</h2>
            <p className="text-sm text-slate-500 mt-1">Gunakan akun yang terdaftar untuk mengakses sistem.</p>
          </div>

          <form onSubmit={handleLogin} className="space-y-5">
            {/* Input Username */}
            <div>
              <label className="block text-xs font-semibold uppercase tracking-wider text-slate-600 mb-2">
                Username
              </label>
              <input
                type="text"
                value={data.username}
                onChange={(e) => setData('username', e.target.value)}
                placeholder="Masukkan username"
                className="w-full px-4 py-2.5 bg-slate-50 border border-slate-200 rounded-xl text-slate-800 placeholder-slate-400 text-sm focus:outline-none focus:border-blue-600 focus:ring-4 focus:ring-blue-600/15 transition duration-200"
                required
              />
            </div>

            {/* Input Password */}
            <div className="relative">
              <label className="block text-xs font-semibold uppercase tracking-wider text-slate-600 mb-2">
                Password
              </label>
              
              <div className="relative flex items-center">
                <input
                  type={passShow ? 'text' : 'password'}
                  value={data.password}
                  onChange={(e) => setData('password', e.target.value)}
                  placeholder="••••••••"
                  className="w-full pl-4 pr-11 py-2.5 bg-slate-50 border border-slate-200 rounded-xl text-slate-800 placeholder-slate-400 text-sm focus:outline-none focus:border-blue-600 focus:ring-4 focus:ring-blue-600/15 transition duration-200"
                  required
                />
                
                <button
                  type="button"
                  onClick={() => setPassShow(!passShow)}
                  className="absolute right-3.5 text-slate-400 hover:text-slate-600 focus:outline-none p-1 transition-colors"
                  aria-label={passShow ? 'Sembunyikan password' : 'Tampilkan password'}
                >
                  {passShow ? <HiEye className="w-5 h-5" /> : <HiEyeOff className="w-5 h-5" />}
                </button>
              </div>

              {errors.password && (
                <p className="text-red-500 text-xs mt-1.5 flex items-center gap-1 font-medium">
                  <span>&bull;</span> {errors.password}
                </p>
              )}
            </div>

            {/* Submit Button */}
            <div className="pt-2">
              <button
                type="submit"
                disabled={processing}
                className="w-full cursor-pointer py-3 px-4 bg-blue-600 hover:bg-blue-700 active:bg-blue-800 text-white font-medium text-sm rounded-xl shadow-lg shadow-blue-600/25 transition duration-200 flex items-center justify-center gap-2 disabled:opacity-60 disabled:cursor-not-allowed"
              >
                {processing ? (
                  <>
                    <svg className="animate-spin h-4 w-4 text-white" fill="none" viewBox="0 0 24 24">
                      <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                      <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                    </svg>
                    <span>Memproses...</span>
                  </>
                ) : (
                  'Masuk ke Sistem'
                )}
              </button>
            </div>
          </form>
        </div>
      </div>

      {/* additional components */}
      {/* Alert Notification saat Error Login / Redirect */}
      {alert && (
        <FailedAlert
          title={alert.title}
          desc={alert.desc}
          duration={5000}
          onClose={() => setAlert(null)}
        />
      )}

    </div>
  );
}