"use client";

import { useState, useEffect, ChangeEvent } from "react";
import { useRouter } from "next/navigation";
import Layout from "@/components/layout/layout";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Save, Send, Key, MessageSquare, Shield } from "lucide-react";
import { apiRequest } from "@/lib/storeHelper";
import { toast, Toaster } from "sonner";
import BroadcastDialog from "@/components/modals/broadcast-dialog";

// ✅ Define the Storefront Type
interface Storefront {
  pgpKey: string;
  welcomeMessage: string;
  telegramToken: string;
}

export default function StorefrontPage() {
  const router = useRouter();
  const [storefront, setStorefront] = useState<Storefront>({
    pgpKey: "",
    welcomeMessage: "",
    telegramToken: "",
  });

  const [broadcastOpen, setBroadcastOpen] = useState<boolean>(false);
  const [loading, setLoading] = useState<boolean>(true);
  const [saving, setSaving] = useState<boolean>(false);

  // ✅ Fetch Storefront Data
  useEffect(() => {
    const authToken = document.cookie
      .split("; ")
      .find((row) => row.startsWith("Authorization="))
      ?.split("=")[1];

    if (!authToken) {
      router.push("/login");
      return;
    }

    const fetchStorefront = async () => {
      try {
        setLoading(true);
        const data: Storefront = await apiRequest("/storefront");
        setStorefront(data);
      } catch (error) {
        toast.error("Failed to load storefront data.");
      } finally {
        setLoading(false);
      }
    };

    fetchStorefront();
  }, []);

  // ✅ Handle Form Input Changes
  const handleInputChange = (
    e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
  ) => {
    setStorefront({ ...storefront, [e.target.name]: e.target.value });
  };

  // ✅ Save Storefront Changes
  const saveStorefront = async () => {
    try {
      setSaving(true);
      await apiRequest("/storefront", "PUT", storefront);
      toast.success("Storefront updated successfully!");
    } catch (error) {
      toast.error("Failed to update storefront.");
    } finally {
      setSaving(false);
    }
  };

  return (
    <Layout>
      <Toaster position="top-right" theme="dark" duration={3000} />
      <BroadcastDialog open={broadcastOpen} setOpen={setBroadcastOpen} />

      <div className="max-w-4xl mx-auto p-6 space-y-8">
        <div className="bg-white dark:bg-[#0F0F12] rounded-xl shadow-lg p-6 border dark:border-zinc-700">
          <div className="flex items-center gap-3 mb-4">
            <Key className="h-6 w-6 text-purple-600 dark:text-purple-400" />
            <h2 className="text-xl font-semibold text-gray-900 dark:text-zinc-100">
              PGP Encryption Key
            </h2>
          </div>
          <div className="space-y-4">
            <Textarea
              name="pgpKey"
              placeholder="-----BEGIN PGP PUBLIC KEY BLOCK-----"
              className="h-48 text-sm bg-gray-50 dark:bg-zinc-900 dark:bg-[#0F0F12]focus:ring-2 focus:ring-purple-500"
              spellCheck={false}
              value={storefront.pgpKey}
              onChange={handleInputChange}
            />
          </div>
        </div>

        {/* Telegram Configuration */}
        <div className="grid gap-6 md:grid-cols-2">
          {/* Bot Token */}
          <div className="bg-white dark:bg-[#0F0F12] rounded-xl shadow-lg p-6 border dark:border-zinc-700">
            <div className="flex items-center gap-3 mb-4">
              <Shield className="h-6 w-6 text-emerald-600 dark:text-emerald-400" />
              <h2 className="text-xl font-semibold text-gray-900 dark:text-zinc-100">
                Telegram Bot Token
              </h2>
            </div>
            <Input
              name="telegramToken"
              type="password"
              placeholder="123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11"
              className="font-mono text-sm bg-gray-50 dark:bg-zinc-900 border-gray-200 dark:border-zinc-700"
              value={storefront.telegramToken}
              onChange={handleInputChange}
            />
          </div>

          {/* Welcome Message */}
          <div className="bg-white dark:bg-[#0F0F12]  rounded-xl shadow-lg p-6 border border-gray-100 dark:border-zinc-700">
            <div className="flex items-center gap-3 mb-4">
              <MessageSquare className="h-6 w-6 text-amber-600 dark:text-amber-400" />
              <h2 className="text-xl font-semibold text-gray-900 dark:text-zinc-100">
                /start Welcome Message
              </h2>
            </div>
            <Textarea
              name="welcomeMessage"
              placeholder="Welcome to our store!"
              className="h-32 text-sm bg-gray-50 dark:bg-zinc-900 border-gray-200 dark:border-zinc-700 focus:ring-2 focus:ring-amber-500"
              value={storefront.welcomeMessage}
              onChange={handleInputChange}
            />
          </div>
        </div>

        <div className="sticky bottom-6 mt-8 flex justify-between">
          <Button
            onClick={() => setBroadcastOpen(true)}
            className="gap-2 bg-emerald-600 hover:bg-emerald-700 text-white"
          >
            <Send className="h-5 w-5" /> Broadcast Message
          </Button>

          <Button
            onClick={saveStorefront}
            disabled={saving}
            className="gap-2 bg-gradient-to-r from-purple-600 to-indigo-600 hover:from-purple-700 hover:to-indigo-700 text-white"
          >
            <Save className="h-5 w-5" />{" "}
            {saving ? "Saving..." : "Save Configuration"}
          </Button>
        </div>
      </div>
    </Layout>
  );
}
