import { createSignal, For } from "solid-js";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, Button, Tabs, TabsList, TabsTrigger, TabsContent, DialogCloseButton } from "./ui";

interface IntegrationModalProps {
  isOpen: boolean;
  onClose: () => void;
  tenantSlug: string;
  publicBookingUrl: string;
  tenantName: string;
  primaryColor?: string;
}

export function IntegrationModal(props: IntegrationModalProps) {
  const [copiedSnippet, setCopiedSnippet] = createSignal<string | null>(null);

  const copyToClipboard = async (text: string, type: string) => {
    await navigator.clipboard.writeText(text);
    setCopiedSnippet(type);
    setTimeout(() => setCopiedSnippet(null), 2000);
  };

  const hostedPageUrl = props.publicBookingUrl;
  const baseUrl = (() => {
    try {
      return new URL(props.publicBookingUrl).origin;
    } catch {
      return "https://bookra.eu";
    }
  })();

  const htmlWidgetCode = `<div id="bookra-widget"></div>
<script>
  (function() {
    var script = document.createElement('script');
    script.src = "${baseUrl}/widget.js";
    script.async = true;
    script.onload = function() {
      BookraWidget.init({
        tenantSlug: "${props.tenantSlug}",
        container: "#bookra-widget",
        theme: "light"
      });
    };
    document.head.appendChild(script);
  })();
</script>`;

  const reactWidgetCode = `import { BookraWidget } from '@bookra/react-widget';

function App() {
  return (
    <BookraWidget
      tenantSlug="${props.tenantSlug}"
      theme="light"
    />
  );
}`;

  const solidWidgetCode = `import { BookraWidget } from '@bookra/solid-widget';

function App() {
  return (
    <BookraWidget
      tenantSlug="${props.tenantSlug}"
      theme="light"
    />
  );
}`;

  const phpWidgetCode = `<?php
// Add to your WordPress functions.php or PHP template
add_action('wp_footer', function() {
?>
<div id="bookra-widget"></div>
<script src="${baseUrl}/widget.js" async></script>
<script>
  window.addEventListener('load', function() {
    BookraWidget.init({
      tenantSlug: "${props.tenantSlug}",
      container: "#bookra-widget",
      theme: "light"
    });
  });
</script>
<?php
});`;

  return (
    <Dialog open={props.isOpen} onClose={props.onClose}>
      <DialogContent class="max-w-3xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle class="text-2xl font-display">
            Add Bookra to Your Website
          </DialogTitle>
          <DialogDescription>
            Choose how you want to integrate Bookra with your business. Share a link or embed directly on your website.
          </DialogDescription>
        </DialogHeader>

        <DialogCloseButton onClose={props.onClose} />
        <Tabs defaultValue="hosted" class="mt-6">
          <TabsList class="grid w-full grid-cols-2">
            <TabsTrigger value="hosted">Hosted Page</TabsTrigger>
            <TabsTrigger value="embed">Embed Widget</TabsTrigger>
          </TabsList>

          <TabsContent value="hosted" class="space-y-6 mt-6">
            <div class="p-6 bg-canvas-subtle rounded-xl border border-border">
              <h4 class="font-display font-semibold text-ink mb-3">Your Booking Page</h4>
              <p class="text-sm text-ink-muted mb-4">
                Share this link with your customers. They can book directly without any setup on your website.
              </p>
              
              <div class="flex items-center gap-3 p-4 bg-canvas rounded-xl border border-border">
                <code class="flex-1 text-sm text-ink truncate font-mono">{hostedPageUrl}</code>
                <Button
                  variant="secondary"
                  size="sm"
                  onClick={() => copyToClipboard(hostedPageUrl, "url")}
                >
                  {copiedSnippet() === "url" ? "Copied!" : "Copy"}
                </Button>
              </div>

              <div class="mt-4 flex items-center gap-2 text-sm text-ink-muted">
                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/>
                  <path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/>
                </svg>
                <span>Perfect for social media, email signatures, or direct sharing</span>
              </div>
            </div>

            <div class="grid grid-cols-2 gap-4">
              <a
                href={`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(hostedPageUrl)}`}
                target="_blank"
                rel="noopener noreferrer"
                class="flex items-center justify-center gap-2 p-3 rounded-xl bg-[hsl(220,70%,55%)]/10 text-[hsl(220,70%,55%)] hover:bg-[hsl(220,70%,55%)]/20 transition-colors"
              >
                <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
                  <path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z"/>
                </svg>
                Share on Facebook
              </a>
              <a
                href={`https://twitter.com/intent/tweet?text=${encodeURIComponent(`Book your appointment with ${props.tenantName}!`)}&url=${encodeURIComponent(hostedPageUrl)}`}
                target="_blank"
                rel="noopener noreferrer"
                class="flex items-center justify-center gap-2 p-3 rounded-xl bg-[hsl(200,15%,10%)]/10 text-ink hover:bg-[hsl(200,15%,10%)]/20 transition-colors"
              >
                <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
                  <path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"/>
                </svg>
                Share on X
              </a>
            </div>
          </TabsContent>

          <TabsContent value="embed" class="space-y-6 mt-6">
            <div class="p-6 bg-canvas-subtle rounded-xl border border-border">
              <h4 class="font-display font-semibold text-ink mb-3">Embed on Your Website</h4>
              <p class="text-sm text-ink-muted mb-4">
                Add the booking widget directly to your website. Choose your platform:
              </p>

              <Tabs defaultValue="html" class="w-full">
                <TabsList class="grid w-full grid-cols-4 mb-4">
                  <TabsTrigger value="html">HTML/JS</TabsTrigger>
                  <TabsTrigger value="react">React</TabsTrigger>
                  <TabsTrigger value="solid">SolidJS</TabsTrigger>
                  <TabsTrigger value="php">PHP/WordPress</TabsTrigger>
                </TabsList>

                <For each={[
                  { id: "html", label: "HTML/JavaScript", code: htmlWidgetCode },
                  { id: "react", label: "React", code: reactWidgetCode },
                  { id: "solid", label: "SolidJS", code: solidWidgetCode },
                  { id: "php", label: "PHP/WordPress", code: phpWidgetCode },
                ]}>
                  {(item) => (
                    <TabsContent value={item.id} class="mt-0">
                      <div class="relative">
                        <pre class="p-4 bg-ink text-canvas rounded-xl overflow-x-auto text-sm font-mono"><code>{item.code}</code></pre>
                        <Button
                          variant="secondary"
                          size="sm"
                          class="absolute top-3 right-3"
                          onClick={() => copyToClipboard(item.code, item.id)}
                        >
                          {copiedSnippet() === item.id ? "Copied!" : "Copy"}
                        </Button>
                      </div>
                    </TabsContent>
                  )}
                </For>
              </Tabs>

              <div class="mt-4 p-4 bg-[hsl(var(--info-subtle))] rounded-xl border border-[hsl(var(--info))/20]">
                <div class="flex items-start gap-3">
                  <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="text-[hsl(var(--info))] mt-0.5 shrink-0">
                    <circle cx="12" cy="12" r="10"/>
                    <line x1="12" x2="12" y1="16" y2="12"/>
                    <line x1="12" x2="12.01" y1="8" y2="8"/>
                  </svg>
                  <div>
                    <p class="text-sm font-medium text-ink">Need help with installation?</p>
                    <p class="text-sm text-ink-muted mt-1">
                      Contact our support team at <a href="mailto:support@bookra.eu" class="text-accent hover:underline">support@bookra.eu</a> for assistance with embedding the widget.
                    </p>
                  </div>
                </div>
              </div>
            </div>
          </TabsContent>
        </Tabs>
      </DialogContent>
    </Dialog>
  );
}
