"use client";
import React, { useEffect, useState, useMemo } from "react";
import { useRouter } from "next/navigation";
import { getCountries } from "@/lib/api/country.api";
import { mapCountriesApiResponse } from "@/lib/api/mappers/country.mappers";
import type { CountryRow } from "@/lib/api/types/country.types";
import { FiArrowLeft, FiDownload, FiGlobe } from "react-icons/fi";
import { FcPrint } from "react-icons/fc";

export default function CountryReportPage() {
  const router = useRouter();
  const [countries, setCountries] = useState<CountryRow[]>([]);
  const [loading, setLoading]     = useState(true);
  const [error, setError]         = useState<string | null>(null);
  const [searchTerm, setSearchTerm] = useState("");

  useEffect(() => {
    setLoading(true);
    getCountries()
      .then((data) => setCountries(mapCountriesApiResponse(data)))
      .catch((err) => setError(err.message))
      .finally(() => setLoading(false));
  }, []);

  const filtered = useMemo(() => countries.filter((c) => {
    const q = searchTerm.toLowerCase();
    return !q || c.name.toLowerCase().includes(q) || c.code.toLowerCase().includes(q);
  }), [countries, searchTerm]);

  if (error) return (
    <div style={{ padding: 40, textAlign: "center" }}>
      <p style={{ color: "#ef4444" }}>{error}</p>
      <button onClick={() => window.location.reload()} style={{ marginTop: 12, padding: "8px 20px", borderRadius: 8, background: "#0f766e", color: "#fff", border: "none", cursor: "pointer" }}>Retry</button>
    </div>
  );

  return (
    <div style={{ padding: "28px 32px", maxWidth: "1100px", margin: "0 auto", fontFamily: "system-ui,sans-serif" }}>

      {/* Header */}
      <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", marginBottom: "24px" }}>
        <div>
          <button onClick={() => router.push("/modules/countries")} style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 13, color: "#6b7280", background: "none", border: "none", cursor: "pointer", marginBottom: 8, padding: 0 }}>
            <FiArrowLeft size={14} /> Back to Countries
          </button>
          <h1 style={{ margin: 0, fontSize: "22px", fontWeight: 800, color: "#111827" }}>🌍 Countries Report</h1>
          <p style={{ margin: "4px 0 0", fontSize: "13px", color: "#6b7280" }}>Overview of all registered countries</p>
        </div>
        <div style={{ display: "flex", gap: 8 }}>
          <button onClick={() => window.print()} style={{ display: "flex", alignItems: "center", gap: 6, padding: "8px 14px", borderRadius: 8, border: "1px solid #e5e7eb", background: "#fff", color: "#374151", fontSize: 13, fontWeight: 600, cursor: "pointer" }}>
            <FcPrint size={16} /> Print
          </button>
          <button style={{ display: "flex", alignItems: "center", gap: 6, padding: "8px 14px", borderRadius: 8, border: "none", background: "linear-gradient(135deg,#0f766e,#14b8a6)", color: "#fff", fontSize: 13, fontWeight: 600, cursor: "pointer" }}>
            <FiDownload size={14} /> Export
          </button>
        </div>
      </div>

      {loading ? (
        <div style={{ textAlign: "center", padding: "80px", color: "#9ca3af" }}>
          <div style={{ fontSize: 32, marginBottom: 12 }}>⏳</div>Loading report...
        </div>
      ) : (
        <>
          {/* KPI Cards */}
          <div style={{ display: "flex", gap: 14, flexWrap: "wrap", marginBottom: "24px" }}>
            {[
              { label: "Total Countries", value: countries.length,                                                        color: "#0f766e", bg: "#f0fdfa" },
              { label: "Middle East",     value: countries.filter((c) => ["AE","SA","QA","OM","BH","KW","IQ","IR"].includes(c.code?.toUpperCase())).length, color: "#2563eb", bg: "#eff6ff" },
              { label: "South Asia",      value: countries.filter((c) => ["PK","IN","BD","LK"].includes(c.code?.toUpperCase())).length,                     color: "#7c3aed", bg: "#f5f3ff" },
              { label: "Other Regions",   value: countries.filter((c) => !["AE","SA","QA","OM","BH","KW","IQ","IR","PK","IN","BD","LK"].includes(c.code?.toUpperCase())).length, color: "#d97706", bg: "#fffbeb" },
            ].map((kpi) => (
              <div key={kpi.label} style={{ padding: "20px 24px", borderRadius: "12px", backgroundColor: kpi.bg, border: `1px solid ${kpi.color}22`, flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: "28px", fontWeight: 800, color: kpi.color }}>{kpi.value}</div>
                <div style={{ fontSize: "12px", color: "#6b7280", marginTop: "4px", fontWeight: 500 }}>{kpi.label}</div>
              </div>
            ))}
          </div>

          {/* Flag Grid */}
          <div style={{ background: "#fff", border: "1px solid #e5e7eb", borderRadius: "14px", padding: "20px", marginBottom: "20px" }}>
            <h3 style={{ margin: "0 0 16px", fontSize: "14px", fontWeight: 700, color: "#111827" }}>Country Flags</h3>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(140px, 1fr))", gap: 10 }}>
              {countries.map((c) => (
                <div key={c.id} style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 6, padding: "12px 8px", borderRadius: 10, border: "1px solid #f3f4f6", background: "#fafafa" }}>
                  {c.flag_url ? (
                    <img src={c.flag_url} alt={c.code} style={{ width: 48, height: 32, objectFit: "cover", borderRadius: 4, border: "1px solid #e5e7eb" }}
                      onError={(e) => { (e.target as HTMLImageElement).style.display = "none"; }} />
                  ) : (
                    <div style={{ width: 48, height: 32, background: "#f3f4f6", borderRadius: 4, display: "flex", alignItems: "center", justifyContent: "center" }}>
                      <FiGlobe size={18} color="#9ca3af" />
                    </div>
                  )}
                  <span style={{ fontSize: 11, fontWeight: 600, color: "#374151", textAlign: "center" }}>{c.name}</span>
                  <span style={{ fontSize: 10, color: "#9ca3af", fontFamily: "monospace", fontWeight: 700 }}>{c.code?.toUpperCase()}</span>
                </div>
              ))}
            </div>
          </div>

          {/* Countries Table */}
          <div style={{ background: "#fff", border: "1px solid #e5e7eb", borderRadius: "14px", overflow: "hidden" }}>
            <div style={{ padding: "16px 20px", borderBottom: "1px solid #f3f4f6", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
              <h3 style={{ margin: 0, fontSize: "14px", fontWeight: 700, color: "#111827" }}>
                All Countries
                <span style={{ marginLeft: 8, padding: "2px 8px", borderRadius: 20, backgroundColor: "#f0fdfa", color: "#0f766e", fontSize: 11, fontWeight: 700 }}>{filtered.length}</span>
              </h3>
              <input value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} placeholder="Search by name or code..." style={{ padding: "6px 12px", border: "1px solid #e5e7eb", borderRadius: 8, fontSize: 12, outline: "none", width: 220 }} />
            </div>
            <table style={{ width: "100%", borderCollapse: "collapse", fontSize: "12px" }}>
              <thead>
                <tr style={{ backgroundColor: "#f9fafb" }}>
                  {["#", "Flag", "Country", "Code", "Registered"].map((h) => (
                    <th key={h} style={{ padding: "10px 16px", textAlign: "left", fontWeight: 700, color: "#6b7280", fontSize: "11px", textTransform: "uppercase", letterSpacing: "0.04em" }}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {filtered.map((c, i) => (
                  <tr key={c.id} style={{ borderBottom: "1px solid #f3f4f6" }}>
                    <td style={{ padding: "10px 16px", color: "#9ca3af", fontWeight: 600 }}>{i + 1}</td>
                    <td style={{ padding: "10px 16px" }}>
                      {c.flag_url ? (
                        <img src={c.flag_url} alt={c.code} style={{ width: 28, height: 19, objectFit: "cover", borderRadius: 3, border: "1px solid #e5e7eb" }}
                          onError={(e) => { (e.target as HTMLImageElement).style.display = "none"; }} />
                      ) : (
                        <FiGlobe size={18} color="#9ca3af" />
                      )}
                    </td>
                    <td style={{ padding: "10px 16px", fontWeight: 600, color: "#111827" }}>{c.name}</td>
                    <td style={{ padding: "10px 16px" }}>
                      <span style={{ padding: "2px 8px", borderRadius: 20, fontSize: 11, fontWeight: 700, backgroundColor: "#f0f9ff", color: "#0369a1", fontFamily: "monospace" }}>{c.code?.toUpperCase()}</span>
                    </td>
                    <td style={{ padding: "10px 16px", color: "#9ca3af", whiteSpace: "nowrap" }}>
                      {c.created_at ? new Date(c.created_at).toLocaleDateString("en-GB", { day: "2-digit", month: "short", year: "numeric" }).replace(/ /g, "-") : "—"}
                    </td>
                  </tr>
                ))}
                {filtered.length === 0 && (
                  <tr><td colSpan={5} style={{ padding: "40px", textAlign: "center", color: "#9ca3af" }}>No countries match your search</td></tr>
                )}
              </tbody>
            </table>
          </div>
        </>
      )}
    </div>
  );
}
