"use client";

import * as React from "react";
import Link from "next/link";
import { toast } from "sonner";
import {
  Loader2,
  Plug,
  Plus,
  CheckCircle2,
  XCircle,
  Clock,
  ExternalLink,
  BookOpen,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  CardDescription,
} from "@/components/ui/card";

type Integration = {
  id: string;
  provider: string;
  name: string;
  enabled: boolean;
  lastSyncAt: string | null;
  lastSyncStatus: string | null;
};

type ProviderInfo = {
  id: string;
  name: string;
  description: string;
  icon: string;
  category: string;
  supportsOAuth: boolean;
};

const PROVIDER_ICONS: Record<string, string> = {
  planning_center: "PCO",
  monday: "M",
  airtable: "AT",
  google_sheets: "GS",
  webhook: "WH",
  csv_export: "CSV",
};

const FEATURED_PROVIDERS = ["planning_center"];

export default function IntegrationsPage() {
  const [integrations, setIntegrations] = React.useState<Integration[]>([]);
  const [providers, setProviders] = React.useState<ProviderInfo[]>([]);
  const [loading, setLoading] = React.useState(true);

  const [fetchError, setFetchError] = React.useState("");

  React.useEffect(() => {
    fetch("/api/integrations")
      .then((r) => {
        if (!r.ok) throw new Error(r.status === 401 ? "org" : "fetch");
        return r.json();
      })
      .then((data) => {
        setIntegrations(data.integrations || []);
        setProviders(data.providers || []);
      })
      .catch((err) => {
        setFetchError(
          err.message === "org"
            ? "Complete onboarding to set up your organization first."
            : "Failed to load integrations."
        );
      })
      .finally(() => setLoading(false));
  }, []);

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20">
        <Loader2 className="size-6 animate-spin text-muted-foreground" />
      </div>
    );
  }

  if (fetchError) {
    return (
      <div className="flex flex-col items-center justify-center gap-3 py-20 text-center">
        <Plug className="size-10 text-muted-foreground/40" />
        <p className="text-sm text-muted-foreground">{fetchError}</p>
      </div>
    );
  }

  const connectedProviderIds = new Set(integrations.map((i) => i.provider));
  const availableProviders = providers.filter(
    (p) => !connectedProviderIds.has(p.id)
  );

  return (
    <div className="space-y-6">
      {/* Docs banner */}
      <Link href="/docs/integrations" className="group block">
        <Card className="glass-card border-primary/20 transition-colors group-hover:border-primary/40">
          <CardContent className="flex items-center gap-3 p-4">
            <div className="flex size-10 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary">
              <BookOpen className="size-4" />
            </div>
            <div className="min-w-0 flex-1">
              <p className="text-sm font-medium">Integration setup guides</p>
              <p className="mt-0.5 text-xs text-muted-foreground">
                Step-by-step instructions for connecting every integration
                Echo OCR supports.
              </p>
            </div>
            <ExternalLink className="size-4 shrink-0 text-muted-foreground transition-transform group-hover:translate-x-0.5" />
          </CardContent>
        </Card>
      </Link>

      {/* Connected Integrations */}
      {integrations.length > 0 && (
        <div className="space-y-3">
          <h3 className="text-sm font-medium text-muted-foreground">
            Connected
          </h3>
          <div className="grid gap-3 sm:grid-cols-2">
            {integrations.map((int) => {
              const provider = providers.find((p) => p.id === int.provider);
              return (
                <Link
                  key={int.id}
                  href={`/settings/integrations/${int.id}`}
                  className="group"
                >
                  <Card className="glass-card transition-colors hover:border-primary/30">
                    <CardContent className="flex items-start gap-4 p-4">
                      <div className="flex size-10 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-xs font-bold text-primary">
                        {PROVIDER_ICONS[int.provider] || "?"}
                      </div>
                      <div className="min-w-0 flex-1">
                        <div className="flex items-center gap-2">
                          <p className="truncate text-sm font-medium">
                            {int.name}
                          </p>
                          {int.enabled ? (
                            <Badge
                              variant="outline"
                              className="border-emerald-500/30 text-emerald-500"
                            >
                              <CheckCircle2 className="mr-1 size-3" />
                              Active
                            </Badge>
                          ) : (
                            <Badge variant="outline" className="text-muted-foreground">
                              Disabled
                            </Badge>
                          )}
                        </div>
                        <p className="mt-0.5 text-xs text-muted-foreground">
                          {provider?.name || int.provider}
                          {int.lastSyncAt && (
                            <>
                              {" · Last sync "}
                              {new Date(int.lastSyncAt).toLocaleDateString()}
                            </>
                          )}
                        </p>
                      </div>
                      <ExternalLink className="size-4 shrink-0 text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100" />
                    </CardContent>
                  </Card>
                </Link>
              );
            })}
          </div>
        </div>
      )}

      {/* Available Providers */}
      <div className="space-y-3">
        <h3 className="text-sm font-medium text-muted-foreground">
          Available Integrations
        </h3>
        <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
          {(availableProviders.length > 0
            ? availableProviders
            : providers
          ).map((provider) => {
            const isConnected = connectedProviderIds.has(provider.id);
            const isFeatured = FEATURED_PROVIDERS.includes(provider.id);
            return (
              <Card
                key={provider.id}
                className={`glass-card relative ${isFeatured ? "border-primary/30" : ""}`}
              >
                {isFeatured && (
                  <span className="absolute -top-2.5 left-4 rounded-full bg-primary px-2 py-0.5 text-[10px] font-bold text-primary-foreground">
                    RECOMMENDED
                  </span>
                )}
                <CardContent className="flex flex-col items-center gap-3 p-5 text-center">
                  <div
                    className={`flex size-12 items-center justify-center rounded-xl text-sm font-bold ${
                      isFeatured
                        ? "bg-primary/20 text-primary"
                        : "bg-muted text-muted-foreground"
                    }`}
                  >
                    {PROVIDER_ICONS[provider.id] || <Plug className="size-5" />}
                  </div>
                  <div>
                    <p className="text-sm font-medium">{provider.name}</p>
                    <p className="mt-0.5 text-xs text-muted-foreground">
                      {provider.description}
                    </p>
                  </div>
                  {isConnected ? (
                    <Badge
                      variant="outline"
                      className="border-emerald-500/30 text-emerald-500"
                    >
                      Connected
                    </Badge>
                  ) : (
                    <Link href={`/settings/integrations/new?provider=${provider.id}`}>
                      <Button variant="outline" size="sm">
                        <Plus className="mr-1.5 size-3.5" />
                        Connect
                      </Button>
                    </Link>
                  )}
                </CardContent>
              </Card>
            );
          })}
        </div>
      </div>
    </div>
  );
}
