"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, Wallet } 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";
import { Switch } from "@/components/ui/switch";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";

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"];
  wallets: {
    bitcoin?: string;
    litecoin: string;
    monero?: string;
  };
  enabledWallets: {
    bitcoin: boolean;
    litecoin: boolean;
    monero: boolean;
  };
}

const WALLET_OPTIONS = [
  {
    id: 'bitcoin',
    name: 'Bitcoin',
    emoji: '₿',
    placeholder: 'Your BTC address',
    disabled: true,
    comingSoon: true
  },
  {
    id: 'litecoin',
    name: 'Litecoin',
    emoji: 'Ł',
    placeholder: 'Your LTC address',
    disabled: false,
    comingSoon: false
  },
  {
    id: 'monero',
    name: 'Monero',
    emoji: 'M',
    placeholder: 'Your XMR address',
    disabled: true,
    comingSoon: true
  },
] as const;

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

  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 = await apiRequest("/storefront");
        setStorefront({
          pgpKey: data.pgpKey || "",
          welcomeMessage: data.welcomeMessage || "",
          telegramToken: data.telegramToken || "",
          shipsFrom: data.shipsFrom || "UK",
          shipsTo: data.shipsTo || "WW",
          wallets: {
            bitcoin: data.wallets?.bitcoin || '',
            litecoin: data.wallets?.litecoin || '',
            monero: data.wallets?.monero || ''
          },
          enabledWallets: {
            bitcoin: data.enabledWallets?.bitcoin || false,
            litecoin: data.enabledWallets?.litecoin || true,
            monero: data.enabledWallets?.monero || false
          }
        });
      } 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>
      <div className="max-w-4xl mx-auto p-6 space-y-6">
        {/* PGP Key Section */}
        <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>
          <Textarea
            value={storefront.pgpKey}
            onChange={(e) => setStorefront(prev => ({ ...prev, pgpKey: e.target.value }))}
            placeholder="Enter your PGP public key"
            className="font-mono text-sm h-40"
          />
        </div>

        {/* Telegram Section */}
        <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">
            <MessageSquare 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
            type="password"
            value={storefront.telegramToken}
            onChange={(e) => setStorefront(prev => ({ ...prev, telegramToken: e.target.value }))}
            placeholder="Enter your Telegram bot token"
          />
        </div>

        {/* Welcome Message Section */}
        <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">
            <MessageSquare 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">
              /start Welcome Message
            </h2>
          </div>
          <Textarea
            value={storefront.welcomeMessage}
            onChange={(e) => setStorefront(prev => ({ ...prev, welcomeMessage: e.target.value }))}
            placeholder="Enter your welcome message"
            className="h-[104px]"
          />
        </div>

        {/* Shipping Locations Section */}
        <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>

        {/* Cryptocurrency Wallets Section */}
        <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">
            <Wallet className="h-6 w-6 text-yellow-600 dark:text-yellow-400" />
            <h2 className="text-xl font-semibold text-gray-900 dark:text-zinc-100">
              Cryptocurrency Wallets
            </h2>
          </div>
          <div className="space-y-4">
            {WALLET_OPTIONS.map((wallet) => (
              <div 
                key={wallet.id}
                className={`p-4 rounded-lg border dark:border-zinc-700 
                  ${wallet.disabled ? 'opacity-60' : ''}`}
              >
                <div className="flex items-center justify-between mb-2">
                  <div className="flex items-center gap-2">
                    <span className="text-lg font-mono">{wallet.emoji}</span>
                    <span className="font-medium">{wallet.name}</span>
                    {wallet.comingSoon && (
                      <span className="text-xs bg-blue-100 dark:bg-blue-900 text-blue-600 dark:text-blue-400 px-2 py-0.5 rounded">
                        Coming Soon
                      </span>
                    )}
                  </div>
                  <TooltipProvider>
                    <Tooltip>
                      <TooltipTrigger asChild>
                        <div>
                          <Switch
                            checked={storefront.enabledWallets[wallet.id]}
                            onCheckedChange={(checked) => 
                              setStorefront(prev => ({
                                ...prev,
                                enabledWallets: {
                                  ...prev.enabledWallets,
                                  [wallet.id]: checked
                                }
                              }))
                            }
                            disabled={wallet.disabled}
                          />
                        </div>
                      </TooltipTrigger>
                      <TooltipContent>
                        {wallet.disabled 
                          ? `${wallet.name} payments coming soon`
                          : `Enable ${wallet.name} payments`
                        }
                      </TooltipContent>
                    </Tooltip>
                  </TooltipProvider>
                </div>
                <Input
                  type="text"
                  placeholder={wallet.placeholder}
                  value={storefront.wallets[wallet.id] || ''}
                  onChange={(e) => 
                    setStorefront(prev => ({
                      ...prev,
                      wallets: {
                        ...prev.wallets,
                        [wallet.id]: e.target.value
                      }
                    }))
                  }
                  disabled={wallet.disabled || !storefront.enabledWallets[wallet.id]}
                  className="font-mono text-sm"
                />
              </div>
            ))}
          </div>
        </div>

        {/* Action Buttons */}
        <div className="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>

        <BroadcastDialog
          open={broadcastOpen}
          setOpen={setBroadcastOpen}
        />
      </div>
    </Layout>
  );
}
