"use client";

import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { RefreshCw, X } from "lucide-react";
import { toast } from "sonner";
import { syncCatalog } from "./actions";

export function SyncButton({ initialCatalogId }: { initialCatalogId: string | null }) {
  const [isOpen, setIsOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const [catalogId, setCatalogId] = useState(initialCatalogId || "");

  async function handleSync() {
    if (!catalogId.trim()) {
      toast.error("Please enter a valid Meta Catalog ID.");
      return;
    }

    setLoading(true);
    try {
      const res = await syncCatalog(catalogId);
      toast.success(`Successfully synced ${res.count} products!`);
      setIsOpen(false);
    } catch (err: any) {
      toast.error(err.message || "Failed to sync catalog");
    } finally {
      setLoading(false);
    }
  }

  function handleOpen() {
    if (initialCatalogId) {
      // If we already have a catalog ID saved, just sync immediately
      handleSync();
    } else {
      // Otherwise, open the modal to ask for it
      setIsOpen(true);
    }
  }

  return (
    <>
      <Button onClick={handleOpen} loading={loading && !!initialCatalogId}>
        <RefreshCw className="h-4 w-4 mr-2" />
        Sync catalog from Meta
      </Button>

      {isOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
          <div className="w-full max-w-md rounded-lg bg-card p-6 shadow-lg">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-bold text-foreground">Connect Meta Catalog</h3>
              <button
                onClick={() => setIsOpen(false)}
                className="text-muted-foreground hover:text-muted-foreground"
              >
                <X className="h-5 w-5" />
              </button>
            </div>
            
            <p className="text-sm text-muted-foreground mb-4">
              Enter your Meta Commerce Catalog ID to import your products. We only need to ask this once.
            </p>

            <div className="space-y-4">
              <div>
                <label className="mb-1 block text-sm font-medium text-muted-foreground">
                  Catalog ID
                </label>
                <Input
                  value={catalogId}
                  onChange={(e) => setCatalogId(e.target.value)}
                  placeholder="e.g. 123456789012345"
                  autoFocus
                />
              </div>

              <div className="flex justify-end gap-3 pt-2">
                <Button variant="ghost" onClick={() => setIsOpen(false)}>
                  Cancel
                </Button>
                <Button onClick={handleSync} loading={loading}>
                  Sync Products
                </Button>
              </div>
            </div>
          </div>
        </div>
      )}
    </>
  );
}
