import { useEffect, useMemo, useState } from "react";
import { AnimatePresence, motion } from "framer-motion";
import {
  AlertTriangle,
  Check,
  Database,
  FileJson,
  Globe2,
  Loader2,
  Plus,
  RefreshCcw,
  Route,
  Server,
  ShieldCheck,
  Zap,
} from "lucide-react";

const API_BASE = import.meta.env.VITE_API_BASE_URL || "http://localhost:4000/api";

const emptyServer = { name: "", ipAddress: "", description: "" };
const emptyService = {
  serverId: "",
  name: "",
  port: "",
  endpoint: "",
  method: "POST",
  requestTemplate: "{}",
  notes: "",
};

const sampleJson = JSON.stringify(
  {
    servers: [
      {
        name: "Billing Server",
        ipAddress: "192.168.1.50",
        services: [
          {
            name: "Invoice API",
            port: 8080,
            endpoint: "/api/invoices/sync",
            method: "POST",
            requestTemplate: { limit: 10 },
          },
        ],
      },
    ],
  },
  null,
  2,
);

async function api(path, options = {}) {
  const response = await fetch(`${API_BASE}${path}`, {
    headers: { "content-type": "application/json", ...(options.headers || {}) },
    ...options,
  });
  const data = await response.json().catch(() => null);
  if (!response.ok) {
    const error = new Error(data?.message || "Request failed.");
    error.data = data;
    throw error;
  }
  return data;
}

function parseJsonField(value) {
  const trimmed = value.trim();
  if (!trimmed) return null;
  return JSON.parse(trimmed);
}

function Stat({ icon: Icon, label, value }) {
  return (
    <div className="flex items-center gap-3 border border-slate-200 bg-white px-4 py-3">
      <span className="flex h-10 w-10 items-center justify-center bg-slate-100 text-slate-700">
        <Icon size={20} />
      </span>
      <div>
        <p className="text-xs font-medium uppercase tracking-wide text-slate-500">{label}</p>
        <p className="text-xl font-semibold text-slate-950">{value}</p>
      </div>
    </div>
  );
}

function Field({ label, children }) {
  return (
    <label className="grid gap-1.5 text-sm font-medium text-slate-700">
      <span>{label}</span>
      {children}
    </label>
  );
}

function App() {
  const [servers, setServers] = useState([]);
  const [serverForm, setServerForm] = useState(emptyServer);
  const [serviceForm, setServiceForm] = useState(emptyService);
  const [jsonInput, setJsonInput] = useState(sampleJson);
  const [preview, setPreview] = useState(null);
  const [message, setMessage] = useState("");
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);
  const [proxyResult, setProxyResult] = useState(null);

  const totals = useMemo(() => {
    const services = servers.reduce((sum, server) => sum + server.services.length, 0);
    const ports = new Set(servers.flatMap((server) => server.services.map((service) => service.port)));
    return { servers: servers.length, services, ports: ports.size };
  }, [servers]);

  async function loadServers() {
    setLoading(true);
    setError("");
    try {
      const data = await api("/servers");
      setServers(data);
      if (data[0] && !serviceForm.serverId) {
        setServiceForm((current) => ({ ...current, serverId: data[0].id }));
      }
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    loadServers();
  }, []);

  async function createServer(event) {
    event.preventDefault();
    setError("");
    setMessage("");
    try {
      await api("/servers", { method: "POST", body: JSON.stringify(serverForm) });
      setServerForm(emptyServer);
      setMessage("Server added.");
      await loadServers();
    } catch (err) {
      setError(err.message);
    }
  }

  async function createService(event) {
    event.preventDefault();
    setError("");
    setMessage("");
    try {
      await api("/services", {
        method: "POST",
        body: JSON.stringify({
          ...serviceForm,
          requestTemplate: parseJsonField(serviceForm.requestTemplate),
        }),
      });
      setServiceForm((current) => ({
        ...emptyService,
        serverId: current.serverId,
        method: "POST",
        requestTemplate: "{}",
      }));
      setMessage("Service added.");
      await loadServers();
    } catch (err) {
      setError(err.message);
    }
  }

  async function previewImport() {
    setError("");
    setMessage("");
    try {
      const payload = JSON.parse(jsonInput);
      const data = await api("/imports/preview", { method: "POST", body: JSON.stringify(payload) });
      setPreview(data);
      setMessage(
        data.conflicts.length
          ? "Conflicts found. Review and confirm before overwrite."
          : "Import is ready. Exact duplicates will be skipped.",
      );
    } catch (err) {
      setError(err.message);
    }
  }

  async function applyImport(mode = "skip") {
    setError("");
    setMessage("");
    try {
      const payload = JSON.parse(jsonInput);
      const data = await api("/imports/apply", {
        method: "POST",
        body: JSON.stringify({ payload, mode }),
      });
      setPreview(null);
      setMessage(
        `Import applied: ${data.applied.serversCreated} servers and ${data.applied.servicesCreated} services created.`,
      );
      await loadServers();
    } catch (err) {
      setError(err.message);
      if (err.data) setPreview(err.data);
    }
  }

  async function reverseProxy(serviceId, body) {
    setError("");
    setProxyResult(null);
    try {
      const data = await api(`/services/${serviceId}/reverse-proxy`, {
        method: "POST",
        body: JSON.stringify({ body }),
      });
      setProxyResult(data);
    } catch (err) {
      setError(err.message);
    }
  }

  return (
    <div className="min-h-screen bg-[#f5f7fb]">
      <header className="border-b border-slate-200 bg-white">
        <div className="mx-auto flex max-w-7xl flex-col gap-6 px-4 py-6 sm:px-6 lg:px-8">
          <div className="flex flex-col justify-between gap-4 lg:flex-row lg:items-center">
            <div className="flex items-center gap-3">
              <span className="flex h-11 w-11 items-center justify-center bg-slate-950 text-white">
                <Route size={22} />
              </span>
              <div>
                <p className="text-sm font-semibold uppercase tracking-wide text-cyan-700">MTC Server Reverse Proxy</p>
                <h1 className="text-2xl font-semibold text-slate-950 sm:text-3xl">Reverse Proxy Manager</h1>
              </div>
            </div>
            <button
              className="inline-flex items-center justify-center gap-2 bg-slate-950 px-4 py-2.5 text-sm font-semibold text-white transition hover:bg-cyan-700"
              onClick={loadServers}
              type="button"
            >
              {loading ? <Loader2 className="animate-spin" size={18} /> : <RefreshCcw size={18} />}
              Refresh
            </button>
          </div>
          <div className="grid gap-3 md:grid-cols-3">
            <Stat icon={Server} label="Servers" value={totals.servers} />
            <Stat icon={Globe2} label="Services" value={totals.services} />
            <Stat icon={Database} label="Ports" value={totals.ports} />
          </div>
        </div>
      </header>

      <main className="mx-auto grid max-w-7xl gap-6 px-4 py-6 sm:px-6 lg:grid-cols-[380px_1fr] lg:px-8">
        <aside className="grid content-start gap-6">
          <section className="border border-slate-200 bg-white p-4">
            <h2 className="mb-4 flex items-center gap-2 text-base font-semibold text-slate-950">
              <Plus size={18} /> Add Server
            </h2>
            <form className="grid gap-3" onSubmit={createServer}>
              <Field label="Server name">
                <input className="border border-slate-300 px-3 py-2 outline-none focus:border-cyan-600" required value={serverForm.name} onChange={(event) => setServerForm({ ...serverForm, name: event.target.value })} />
              </Field>
              <Field label="IP address">
                <input className="border border-slate-300 px-3 py-2 outline-none focus:border-cyan-600" required value={serverForm.ipAddress} onChange={(event) => setServerForm({ ...serverForm, ipAddress: event.target.value })} />
              </Field>
              <Field label="Description">
                <textarea className="min-h-20 border border-slate-300 px-3 py-2 outline-none focus:border-cyan-600" value={serverForm.description} onChange={(event) => setServerForm({ ...serverForm, description: event.target.value })} />
              </Field>
              <button className="inline-flex items-center justify-center gap-2 bg-cyan-700 px-4 py-2.5 text-sm font-semibold text-white hover:bg-slate-950">
                <Check size={18} /> Save Server
              </button>
            </form>
          </section>

          <section className="border border-slate-200 bg-white p-4">
            <h2 className="mb-4 flex items-center gap-2 text-base font-semibold text-slate-950">
              <Zap size={18} /> Add Service
            </h2>
            <form className="grid gap-3" onSubmit={createService}>
              <Field label="Server">
                <select className="border border-slate-300 px-3 py-2 outline-none focus:border-cyan-600" required value={serviceForm.serverId} onChange={(event) => setServiceForm({ ...serviceForm, serverId: event.target.value })}>
                  <option value="">Select server</option>
                  {servers.map((server) => (
                    <option key={server.id} value={server.id}>
                      {server.name} ({server.ipAddress})
                    </option>
                  ))}
                </select>
              </Field>
              <Field label="Service name">
                <input className="border border-slate-300 px-3 py-2 outline-none focus:border-cyan-600" required value={serviceForm.name} onChange={(event) => setServiceForm({ ...serviceForm, name: event.target.value })} />
              </Field>
              <div className="grid grid-cols-[1fr_110px] gap-3">
                <Field label="Endpoint">
                  <input className="border border-slate-300 px-3 py-2 outline-none focus:border-cyan-600" required value={serviceForm.endpoint} onChange={(event) => setServiceForm({ ...serviceForm, endpoint: event.target.value })} />
                </Field>
                <Field label="Port">
                  <input className="border border-slate-300 px-3 py-2 outline-none focus:border-cyan-600" required min="1" max="65535" type="number" value={serviceForm.port} onChange={(event) => setServiceForm({ ...serviceForm, port: event.target.value })} />
                </Field>
              </div>
              <Field label="Request JSON">
                <textarea className="min-h-24 border border-slate-300 px-3 py-2 font-mono text-xs outline-none focus:border-cyan-600" value={serviceForm.requestTemplate} onChange={(event) => setServiceForm({ ...serviceForm, requestTemplate: event.target.value })} />
              </Field>
              <button className="inline-flex items-center justify-center gap-2 bg-slate-950 px-4 py-2.5 text-sm font-semibold text-white hover:bg-cyan-700">
                <Check size={18} /> Save Service
              </button>
            </form>
          </section>

          <section className="border border-slate-200 bg-white p-4">
            <h2 className="mb-4 flex items-center gap-2 text-base font-semibold text-slate-950">
              <FileJson size={18} /> JSON Import
            </h2>
            <textarea className="min-h-80 w-full border border-slate-300 px-3 py-2 font-mono text-xs outline-none focus:border-cyan-600" value={jsonInput} onChange={(event) => setJsonInput(event.target.value)} />
            <div className="mt-3 grid grid-cols-2 gap-3">
              <button className="border border-slate-300 bg-white px-4 py-2 text-sm font-semibold text-slate-800 hover:border-cyan-700" onClick={previewImport} type="button">
                Preview
              </button>
              <button className="bg-cyan-700 px-4 py-2 text-sm font-semibold text-white hover:bg-slate-950" onClick={() => applyImport("skip")} type="button">
                Add New
              </button>
            </div>
          </section>
        </aside>

        <section className="grid content-start gap-6">
          <AnimatePresence>
            {(message || error) && (
              <motion.div animate={{ opacity: 1, y: 0 }} className={`border p-4 text-sm font-medium ${error ? "border-rose-200 bg-rose-50 text-rose-800" : "border-emerald-200 bg-emerald-50 text-emerald-800"}`} exit={{ opacity: 0, y: -8 }} initial={{ opacity: 0, y: -8 }}>
                {error || message}
              </motion.div>
            )}
          </AnimatePresence>

          {preview && (
            <section className="border border-slate-200 bg-white p-4">
              <div className="flex flex-col justify-between gap-3 md:flex-row md:items-center">
                <h2 className="flex items-center gap-2 text-base font-semibold text-slate-950">
                  {preview.conflicts?.length ? <AlertTriangle size={18} /> : <ShieldCheck size={18} />}
                  Import Preview
                </h2>
                {preview.conflicts?.length > 0 && (
                  <button className="bg-amber-600 px-4 py-2 text-sm font-semibold text-white hover:bg-slate-950" onClick={() => applyImport("overwrite")} type="button">
                    Confirm Overwrite
                  </button>
                )}
              </div>
              <div className="mt-4 grid gap-3 md:grid-cols-3">
                <Stat icon={Plus} label="New servers" value={preview.newServers?.length || 0} />
                <Stat icon={Zap} label="New services" value={preview.newServices?.length || 0} />
                <Stat icon={AlertTriangle} label="Conflicts" value={preview.conflicts?.length || 0} />
              </div>
            </section>
          )}

          <div className="grid gap-4">
            {servers.map((server) => (
              <motion.article animate={{ opacity: 1, y: 0 }} className="border border-slate-200 bg-white p-4" initial={{ opacity: 0, y: 8 }} key={server.id}>
                <div className="flex flex-col justify-between gap-3 border-b border-slate-200 pb-4 md:flex-row md:items-start">
                  <div>
                    <h2 className="text-lg font-semibold text-slate-950">{server.name}</h2>
                    <p className="mt-1 font-mono text-sm text-slate-600">{server.ipAddress}</p>
                    {server.description && <p className="mt-2 text-sm text-slate-600">{server.description}</p>}
                  </div>
                  <span className="bg-slate-100 px-3 py-1 text-sm font-semibold text-slate-700">{server.services.length} services</span>
                </div>
                <div className="mt-4 grid gap-3 xl:grid-cols-2">
                  {server.services.map((service) => (
                    <div className="border border-slate-200 p-3" key={service.id}>
                      <div className="flex items-start justify-between gap-3">
                        <div>
                          <h3 className="font-semibold text-slate-950">{service.name}</h3>
                          <p className="mt-1 break-all font-mono text-xs text-slate-600">
                            {service.method} http://{server.ipAddress}:{service.port}
                            {service.endpoint}
                          </p>
                        </div>
                        <button className="inline-flex shrink-0 items-center gap-2 bg-slate-950 px-3 py-2 text-xs font-semibold text-white hover:bg-cyan-700" onClick={() => reverseProxy(service.id, service.requestTemplate)} type="button">
                          <Route size={15} /> Reverse Proxy
                        </button>
                      </div>
                    </div>
                  ))}
                  {server.services.length === 0 && <p className="border border-dashed border-slate-300 p-4 text-sm text-slate-500">No services added for this server yet.</p>}
                </div>
              </motion.article>
            ))}
          </div>

          {servers.length === 0 && !loading && <section className="border border-dashed border-slate-300 bg-white p-8 text-center text-slate-600">Add a server manually or import JSON to start building the proxy table.</section>}

          {proxyResult && (
            <section className="border border-slate-200 bg-white p-4">
              <h2 className="mb-3 text-base font-semibold text-slate-950">Reverse Proxy Result</h2>
              <pre className="max-h-96 overflow-auto bg-slate-950 p-4 text-xs text-slate-50">{JSON.stringify(proxyResult, null, 2)}</pre>
            </section>
          )}
        </section>
      </main>
    </div>
  );
}

export default App;
