"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, Globe } from "lucide-react";
import { apiRequest } from "@/lib/storeHelper";
import { toast, Toaster } from "sonner";
import BroadcastDialog from "@/components/modals/broadcast-dialog";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";

const SHIPPING_REGIONS = [
  { value: "UK", label: "United Kingdom", emoji: "🇬🇧" },
  { value: "EU", label: "European Union", emoji: "🇪🇺" },
  { value: "USA", label: "United States", emoji: "🇺🇸" },
  { value: "WW", label: "Worldwide", emoji: "🌍" },
] as const;

interface Storefront {
  pgpKey: string;
  welcomeMessage: string;
  telegramToken: string;
  shipsFrom: typeof SHIPPING_REGIONS[number]["value"];
  shipsTo: typeof SHIPPING_REGIONS[number]["value"];
}

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

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

  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="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">
            <Globe className="h-6 w-6 text-blue-600 dark:text-blue-400" />
            <h2 className="text-xl font-semibold text-gray-900 dark:text-zinc-100">
              Shipping Locations
            </h2>
          </div>
          <div className="grid grid-cols-2 gap-6">
            <div className="space-y-2">
              <label className="text-sm font-medium">Ships From</label>
              <Select
                value={storefront.shipsFrom}
                onValueChange={(value: typeof SHIPPING_REGIONS[number]["value"]) => 
                  setStorefront(prev => ({ ...prev, shipsFrom: value }))
                }
              >
                <SelectTrigger>
                  <SelectValue>
                    {storefront.shipsFrom && (
                      <div className="flex items-center gap-2">
                        <span>{SHIPPING_REGIONS.find(r => r.value === storefront.shipsFrom)?.emoji}</span>
                        <span>{SHIPPING_REGIONS.find(r => r.value === storefront.shipsFrom)?.label}</span>
                      </div>
                    )}
                  </SelectValue>
                </SelectTrigger>
                <SelectContent>
                  {SHIPPING_REGIONS.map((region) => (
                    <SelectItem key={region.value} value={region.value}>
                      <div className="flex items-center gap-2">
                        <span>{region.emoji}</span>
                        <span>{region.label}</span>
                      </div>
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div className="space-y-2">
              <label className="text-sm font-medium">Ships To</label>
              <Select
                value={storefront.shipsTo}
                onValueChange={(value: typeof SHIPPING_REGIONS[number]["value"]) => 
                  setStorefront(prev => ({ ...prev, shipsTo: value }))
                }
              >
                <SelectTrigger>
                  <SelectValue>
                    {storefront.shipsTo && (
                      <div className="flex items-center gap-2">
                        <span>{SHIPPING_REGIONS.find(r => r.value === storefront.shipsTo)?.emoji}</span>
                        <span>{SHIPPING_REGIONS.find(r => r.value === storefront.shipsTo)?.label}</span>
                      </div>
                    )}
                  </SelectValue>
                </SelectTrigger>
                <SelectContent>
                  {SHIPPING_REGIONS.map((region) => (
                    <SelectItem key={region.value} value={region.value}>
                      <div className="flex items-center gap-2">
                        <span>{region.emoji}</span>
                        <span>{region.label}</span>
                      </div>
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </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>
  );
}
