'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { api } from '@/lib/api';
import { useAuth } from '@/components/auth-context';
import { toast } from 'react-toastify';
import BackToDashboard from '@/components/BackToDashboard';

interface AtRiskUser {
  id: number;
  email: string;
  full_name: string;
  role: string;
  password_expiry_date: string | null;
  password_expired: boolean;
  days_remaining: number | null;
}

interface PolicyStats {
  total_with_policy: number;
  expired: number;
  expiring_soon: number;
  active: number;
  at_risk_users: AtRiskUser[];
}

const PRESET_OPTIONS = [90, 60, 40, 20];

export default function PasswordPolicyPage() {
  const router = useRouter();
  const { user: me } = useAuth();
  const [loading, setLoading] = useState(true);
  const [currentDays, setCurrentDays] = useState<number | null>(null);
  const [dropdownValue, setDropdownValue] = useState<string>('90');
  const [customInput, setCustomInput] = useState('');
  const [saving, setSaving] = useState(false);
  const [stats, setStats] = useState<PolicyStats | null>(null);
  const [statsLoading, setStatsLoading] = useState(true);
  const isOther = dropdownValue === 'other';
  const rawValue = isOther ? customInput : dropdownValue;
  const parsedDays = parseInt(rawValue, 10);
  const isValidInput = !isNaN(parsedDays) && parsedDays >= 1 && parsedDays <= 365;
  const isDirty = isValidInput && parsedDays !== currentDays;

  useEffect(() => {
    if (!me) return;
    async function load() {
      try {
        if (me!.role !== 'ADMIN') {
          router.replace('/dashboard');
          return;
        }

        const [policyRes, statsRes] = await Promise.all([
          api.get('/auth/password/policy/') as any,
          api.get('/auth/password/policy/stats/') as any,
        ]);

        const days = policyRes.data.expiry_days;
        setCurrentDays(days);
        if (PRESET_OPTIONS.includes(days)) {
          setDropdownValue(String(days));
        } else {
          setDropdownValue('other');
          setCustomInput(String(days));
        }
        setStats(statsRes.data);
      } catch {
        router.replace('/dashboard');
      } finally {
        setLoading(false);
        setStatsLoading(false);
      }
    }
    load();
  }, [me, router]);

  const handleSave = async () => {
    if (!isValidInput || !isDirty) return;
    setSaving(true);
    try {
      await api.patch('/auth/password/policy/', { expiry_days: parsedDays });
      setCurrentDays(parsedDays);
      toast.success(`Password expiry set to ${parsedDays} days.`);
    } catch (err: any) {
      toast.error(err.message || 'Failed to update policy.');
    } finally {
      setSaving(false);
    }
  };

  if (loading || !me) return null;

  return (
        <main className="flex-1 overflow-y-auto p-6 space-y-6">
          <BackToDashboard />

          {/* Page header */}
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-none bg-indigo-100 dark:bg-indigo-950/40 flex items-center justify-center shrink-0">
              <i className="fa-solid fa-lock text-indigo-600 dark:text-indigo-400 text-base" />
            </div>
            <div>
              <h1 className="text-xl font-black text-slate-900 dark:text-white">Password Policy</h1>
              <p className="text-xs text-slate-500 dark:text-slate-400 mt-0.5">
                Set how frequently users must change their password.
              </p>
            </div>
          </div>

          {/* Current policy banner */}
          {currentDays && (
            <div className="flex items-center gap-3 px-5 py-3.5 bg-emerald-50 dark:bg-emerald-950/20 border border-emerald-200 dark:border-emerald-900/30 rounded-none">
              <i className="fa-solid fa-circle-check text-emerald-500 dark:text-emerald-400 text-base" />
              <p className="text-sm font-semibold text-emerald-800 dark:text-emerald-300">
                Current policy: passwords expire every{' '}
                <span className="font-black">{currentDays} days</span>
              </p>
            </div>
          )}

          {/* Input card */}
          <div className="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-none p-6 max-w-sm space-y-4">
            <div className="space-y-3">
              <label className="block text-xs font-extrabold uppercase tracking-wider text-slate-500 dark:text-slate-400">
                Expiry Duration (days)
              </label>

              {/* Dropdown */}
              <div className="relative">
                <select
                  value={dropdownValue}
                  onChange={(e) => {
                    setDropdownValue(e.target.value);
                    if (e.target.value !== 'other') setCustomInput('');
                  }}
                  className="w-full appearance-none bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-none px-4 py-2.5 pr-10 text-sm font-bold text-slate-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-indigo-500/30 focus:border-indigo-500 transition cursor-pointer [&>option]:bg-white [&>option]:dark:bg-slate-800 [&>option]:text-slate-900 [&>option]:dark:text-white"
                >
                  <option value="90">90 days — Quarterly (Default)</option>
                  <option value="60">60 days — Bi-monthly</option>
                  <option value="40">40 days</option>
                  <option value="20">20 days</option>
                  <option value="other">Other — Enter custom days</option>
                </select>
                <i className="fa-solid fa-chevron-down absolute right-3.5 top-1/2 -translate-y-1/2 text-slate-400 text-[11px] pointer-events-none" />
              </div>

              {/* Custom input — shown only when "Other" is selected */}
              {isOther && (
                <div className="flex items-center gap-3">
                  <input
                    type="number"
                    min={1}
                    max={365}
                    placeholder="e.g. 45"
                    value={customInput}
                    onChange={(e) => setCustomInput(e.target.value)}
                    className="w-32 bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-none px-4 py-2.5 text-xl font-black text-slate-900 dark:text-white placeholder:text-slate-400 dark:placeholder:text-slate-500 focus:outline-none focus:ring-2 focus:ring-indigo-500/30 focus:border-indigo-500 text-center transition"
                    autoFocus
                  />
                  <span className="text-sm font-bold text-slate-400 dark:text-slate-500">days</span>
                </div>
              )}

              {isOther && customInput !== '' && !isValidInput && (
                <p className="text-[11px] text-rose-500 font-semibold">
                  Enter a number between 1 and 365.
                </p>
              )}
            </div>

            <div className="flex items-center gap-3">
              <button
                onClick={handleSave}
                disabled={saving || !isDirty || !isValidInput}
                className="flex items-center gap-2 px-5 py-2.5 rounded-none text-sm font-extrabold text-white transition disabled:opacity-40 cursor-pointer"
                style={{
                  background: 'linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%)',
                  boxShadow: '0 4px 14px rgba(99,102,241,0.3)',
                }}
              >
                {saving ? (
                  <><i className="fa-solid fa-spinner fa-spin" /> Saving...</>
                ) : (
                  <><i className="fa-solid fa-floppy-disk" /> Save</>
                )}
              </button>
              {isDirty && isValidInput && (
                <p className="text-[11px] text-amber-600 dark:text-amber-400 font-semibold">
                  <i className="fa-solid fa-triangle-exclamation mr-1" />
                  Unsaved changes
                </p>
              )}
            </div>
          </div>

          {/* Info note */}
          <div className="p-4 bg-slate-100 dark:bg-slate-800/50 border border-slate-200 dark:border-slate-800 rounded-none text-xs text-slate-500 dark:text-slate-400 leading-relaxed">
            <i className="fa-solid fa-circle-info mr-1.5 text-indigo-400" />
            Changing the policy only affects passwords set <strong>after</strong> this change. Existing users keep
            their current expiry dates until they next change their password.
          </div>

          {/* Stats cards */}
          {!statsLoading && stats && (
            <>
              <div>
                <h2 className="text-sm font-black text-slate-700 dark:text-slate-300 mb-3">
                  Password Policy Overview
                </h2>
                <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
                  {[
                    {
                      label: 'Policy Enabled',
                      value: stats.total_with_policy,
                      icon: 'fa-shield-halved',
                      color: 'text-indigo-600 dark:text-indigo-400',
                      bg: 'bg-indigo-50 dark:bg-indigo-950/30',
                    },
                    {
                      label: 'Active',
                      value: stats.active,
                      icon: 'fa-circle-check',
                      color: 'text-emerald-600 dark:text-emerald-400',
                      bg: 'bg-emerald-50 dark:bg-emerald-950/30',
                    },
                    {
                      label: 'Expiring Soon',
                      value: stats.expiring_soon,
                      icon: 'fa-clock',
                      color: 'text-amber-600 dark:text-amber-400',
                      bg: 'bg-amber-50 dark:bg-amber-950/30',
                    },
                    {
                      label: 'Expired',
                      value: stats.expired,
                      icon: 'fa-circle-xmark',
                      color: 'text-rose-600 dark:text-rose-400',
                      bg: 'bg-rose-50 dark:bg-rose-950/30',
                    },
                  ].map((s) => (
                    <div
                      key={s.label}
                      className="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-none p-5 flex items-center gap-4"
                    >
                      <div className={`w-10 h-10 rounded-none flex items-center justify-center shrink-0 ${s.bg}`}>
                        <i className={`fa-solid ${s.icon} ${s.color} text-base`} />
                      </div>
                      <div>
                        <div className="text-2xl font-black text-slate-900 dark:text-white">{s.value}</div>
                        <div className="text-[11px] font-semibold text-slate-400 dark:text-slate-500">{s.label}</div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>

              {/* At-risk users table */}
              <div>
                <h2 className="text-sm font-black text-slate-700 dark:text-slate-300 mb-3">
                  Users — Expired or Expiring Within 7 Days
                </h2>
                {stats.at_risk_users.length === 0 ? (
                  <div className="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-none p-8 text-center text-sm text-slate-400 dark:text-slate-500">
                    <i className="fa-solid fa-circle-check text-emerald-400 text-2xl mb-2 block" />
                    All users are well within their password expiry period.
                  </div>
                ) : (
                  <div className="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-none overflow-hidden">
                    <div className="overflow-x-auto">
                      <table className="w-full text-sm">
                        <thead>
                          <tr className="border-b border-slate-100 dark:border-slate-800 bg-slate-50 dark:bg-slate-800/50">
                            <th className="text-left px-5 py-3 text-[10px] font-extrabold uppercase tracking-wider text-slate-400">User</th>
                            <th className="text-left px-5 py-3 text-[10px] font-extrabold uppercase tracking-wider text-slate-400">Role</th>
                            <th className="text-left px-5 py-3 text-[10px] font-extrabold uppercase tracking-wider text-slate-400">Expiry Date</th>
                            <th className="text-left px-5 py-3 text-[10px] font-extrabold uppercase tracking-wider text-slate-400">Days Left</th>
                            <th className="text-left px-5 py-3 text-[10px] font-extrabold uppercase tracking-wider text-slate-400">Status</th>
                          </tr>
                        </thead>
                        <tbody className="divide-y divide-slate-100 dark:divide-slate-800">
                          {stats.at_risk_users.map((u) => (
                            <tr key={u.id} className="hover:bg-slate-50 dark:hover:bg-slate-800/30 transition">
                              <td className="px-5 py-3.5">
                                <div className="font-semibold text-slate-900 dark:text-white text-xs">
                                  {u.full_name || '—'}
                                </div>
                                <div className="text-[11px] text-slate-400">{u.email}</div>
                              </td>
                              <td className="px-5 py-3.5">
                                <span className="text-[10px] font-extrabold uppercase tracking-wider px-2 py-0.5 rounded-full bg-slate-100 dark:bg-slate-800 text-slate-500 dark:text-slate-400">
                                  {u.role}
                                </span>
                              </td>
                              <td className="px-5 py-3.5 text-xs text-slate-600 dark:text-slate-300 font-medium">
                                {u.password_expiry_date ?? '—'}
                              </td>
                              <td className="px-5 py-3.5 text-xs font-black">
                                {u.password_expired ? (
                                  <span className="text-rose-500">Expired</span>
                                ) : (
                                  <span className={u.days_remaining !== null && u.days_remaining <= 3 ? 'text-rose-500' : 'text-amber-500'}>
                                    {u.days_remaining}d
                                  </span>
                                )}
                              </td>
                              <td className="px-5 py-3.5">
                                {u.password_expired ? (
                                  <span className="inline-flex items-center gap-1 text-[10px] font-extrabold px-2 py-0.5 rounded-full bg-rose-100 dark:bg-rose-950/40 text-rose-600 dark:text-rose-400">
                                    <i className="fa-solid fa-circle-xmark text-[8px]" /> Expired
                                  </span>
                                ) : (
                                  <span className="inline-flex items-center gap-1 text-[10px] font-extrabold px-2 py-0.5 rounded-full bg-amber-100 dark:bg-amber-950/40 text-amber-600 dark:text-amber-400">
                                    <i className="fa-solid fa-clock text-[8px]" /> Expiring Soon
                                  </span>
                                )}
                              </td>
                            </tr>
                          ))}
                        </tbody>
                      </table>
                    </div>
                  </div>
                )}
              </div>
            </>
          )}

        </main>
  );
}
