import { Button, Card, Input, Label, Separator, toast } from "@heroui/react";
import { useEffect, useState } from "react";
import AdminLayout from "components/layout/AdminLayout";
import axios from "axios";
import { Icon } from "@iconify/react";

// Hosting providers are discovered dynamically: every Who Is Hosting lookup
// records the detected provider. Here the admin assigns an affiliate link to
// each one; the public checker then surfaces that link whenever the same
// provider is detected again.
export default function HostingAffiliates() {
  const [providers, setProviders] = useState([]);
  const [fetching, setFetching] = useState(true);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    axios
      .get("/api/hosting-providers")
      .then((res) => setProviders(res.data?.providers || []))
      .catch((err) => console.log(err))
      .finally(() => setFetching(false));
  }, []);

  const updateLink = (key, value) =>
    setProviders((prev) =>
      prev.map((p) => (p.key === key ? { ...p, affiliateLink: value } : p)),
    );

  const handleSave = () => {
    setLoading(true);
    axios
      .post("/api/hosting-providers", {
        providers: providers.map((p) => ({
          key: p.key,
          affiliateLink: p.affiliateLink || "",
        })),
      })
      .then((res) => {
        setLoading(false);
        toast.success(res.data?.message || "Saved");
      })
      .catch((err) => {
        setLoading(false);
        console.log(err);
        toast.error("Some error occurred.");
      });
  };

  const formatDate = (v) => {
    if (!v) return "—";
    const d = new Date(v);
    return isNaN(d.getTime()) ? "—" : d.toLocaleDateString();
  };

  return (
    <AdminLayout>
      <Card>
        <Card.Header className="flex flex-col gap-1">
          <h4 className="text-xl font-semibold">Hosting Affiliate Links</h4>
          <p className="text-sm text-gray-500">
            Providers detected by the Who Is Hosting checker. Assign an
            affiliate link to any provider and it will be shown on the front end
            whenever that provider is detected.
          </p>
        </Card.Header>
        <Separator />
        <Card.Content className="flex flex-col gap-3">
          {fetching ? (
            <div className="flex items-center gap-2 py-8 text-sm text-gray-500">
              <Icon className="size-4 animate-spin" icon="mdi:loading" />
              Loading detected providers…
            </div>
          ) : providers.length === 0 ? (
            <div className="flex flex-col items-center gap-2 py-12 text-center">
              <Icon className="size-8 text-gray-400" icon="mdi:server-off" />
              <p className="text-sm text-gray-500">
                No hosting providers detected yet. Run a few lookups on the{" "}
                <span className="font-medium">Who Is Hosting</span> page and they
                will appear here.
              </p>
            </div>
          ) : (
            providers.map((p) => (
              <div
                key={p.key}
                className="flex flex-col gap-3 rounded-xl border border-gray-200 p-4 md:flex-row md:items-end md:justify-between"
              >
                <div className="flex min-w-0 flex-col gap-1">
                  <div className="flex items-center gap-2">
                    <Icon
                      className="size-4 text-gray-500"
                      icon="mdi:server-network"
                    />
                    <span className="font-medium truncate">{p.name}</span>
                  </div>
                  <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-gray-500">
                    {p.asn && <span className="font-mono">{p.asn}</span>}
                    <span>Detected {p.count || 0}×</span>
                    <span>Last seen {formatDate(p.lastSeen)}</span>
                  </div>
                </div>
                <div className="flex w-full flex-col gap-1 md:max-w-md">
                  <Label>Affiliate Link</Label>
                  <Input
                    variant="secondary"
                    value={p.affiliateLink || ""}
                    onChange={(e) => updateLink(p.key, e.target.value)}
                    type="text"
                    placeholder="https://provider.com/?ref=your-affiliate-id"
                  />
                </div>
              </div>
            ))
          )}
        </Card.Content>
        <Separator />
        <Card.Footer>
          <Button
            size="lg"
            className="rounded-2xl px-6 mt-4"
            isPending={loading}
            isDisabled={providers.length === 0}
            onPress={handleSave}
          >
            Save
          </Button>
        </Card.Footer>
      </Card>
    </AdminLayout>
  );
}
