import { useState } from 'react';
import { ExternalLink, Copy, Check, RefreshCw } from 'lucide-react';
import {
  Button,
  Skeleton,
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
  cn,
  useToast,
} from '@insforge/ui';
import { useDeployments } from '#features/deployments/hooks/useDeployments';
import { useDeploymentMetadata } from '#features/deployments/hooks/useDeploymentMetadata';
import { useCopyToClipboard } from '#lib/hooks/useCopyToClipboard';
import { useCustomDomains } from '#features/deployments/hooks/useCustomDomains';
import { formatTime } from '#lib/utils/utils';

const statusColors: Record<string, string> = {
  WAITING: 'bg-yellow-600',
  UPLOADING: 'bg-blue-600',
  QUEUED: 'bg-purple-600',
  BUILDING: 'bg-sky-600',
  READY: 'bg-green-700',
  ERROR: 'bg-red-600',
  CANCELED: 'bg-gray-500',
};

const DEPLOY_PROMPT = 'Deploy my app to InsForge';

export default function DeploymentOverviewPage() {
  const { showToast } = useToast();
  const { copied, copy } = useCopyToClipboard();
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [iframeKey, setIframeKey] = useState(0);
  const { deployments, isLoadingDeployments, refetchDeployments } = useDeployments();
  const { customDomainUrl } = useDeploymentMetadata();
  const { domains: customDomains } = useCustomDomains();

  const latestReadyDeployment = deployments.find((d) => d.status === 'READY') ?? null;

  const statusColor = latestReadyDeployment
    ? statusColors[latestReadyDeployment.status] || 'bg-gray-500'
    : 'bg-gray-500';

  const deploymentUrl = latestReadyDeployment?.url
    ? latestReadyDeployment.url.startsWith('http')
      ? latestReadyDeployment.url
      : `https://${latestReadyDeployment.url}`
    : null;
  const readyCustomDomains = customDomains
    .filter((domain) => domain.verified && !domain.misconfigured)
    .sort((left, right) => left.domain.localeCompare(right.domain));
  const preferredCustomDomain = readyCustomDomains[0] ?? null;
  const visibleDomains = [
    ...readyCustomDomains.map((domain) => ({
      href: `https://${domain.domain}`,
      label: `https://${domain.domain}`,
    })),
    ...(customDomainUrl
      ? [
          {
            href: customDomainUrl,
            label: customDomainUrl,
          },
        ]
      : []),
    ...(deploymentUrl && latestReadyDeployment?.url
      ? [
          {
            href: deploymentUrl,
            label: latestReadyDeployment.url,
          },
        ]
      : []),
  ];
  const primaryVisitUrl = preferredCustomDomain
    ? `https://${preferredCustomDomain.domain}`
    : (customDomainUrl ?? deploymentUrl);

  const handleRefresh = async () => {
    setIsRefreshing(true);
    setIframeKey((prev) => prev + 1);
    try {
      await refetchDeployments();
    } finally {
      setIsRefreshing(false);
    }
  };

  const handleCopyPrompt = async () => {
    const ok = await copy(DEPLOY_PROMPT);
    if (!ok) {
      showToast('Failed to copy to clipboard', 'error');
    }
  };

  const renderContent = () => {
    if (isLoadingDeployments) {
      return <Skeleton className="h-[352px] w-full rounded-lg" />;
    }

    if (!latestReadyDeployment) {
      return (
        <div className="bg-neutral-100 dark:bg-[#333] rounded-lg p-6">
          <div className="flex flex-col gap-6">
            <h2 className="text-xl font-semibold text-zinc-950 dark:text-white">
              No deployments yet
            </h2>

            <div className="flex flex-col gap-3">
              <p className="text-sm text-muted-foreground dark:text-neutral-400">
                Send the prompt below to your connected AI agent to deploy your site for the first
                time.
              </p>

              <div className="bg-neutral-200 dark:bg-[#171717] rounded-lg p-3 flex flex-col gap-2">
                <div className="flex items-start">
                  <span className="bg-neutral-300 dark:bg-neutral-700 text-zinc-950 dark:text-neutral-50 text-xs px-2 py-0.5 rounded">
                    prompt
                  </span>
                </div>
                <div className="flex items-center justify-between">
                  <p className="text-sm text-zinc-950 dark:text-white">{DEPLOY_PROMPT}</p>
                  <Button
                    variant="secondary"
                    size="sm"
                    onClick={() => void handleCopyPrompt()}
                    className="bg-neutral-100 dark:bg-neutral-800 hover:bg-neutral-200 dark:hover:bg-neutral-700"
                  >
                    {copied ? (
                      <Check className="w-4 h-4 mr-2" />
                    ) : (
                      <Copy className="w-4 h-4 mr-2" />
                    )}
                    {copied ? 'Copied' : 'Copy'}
                  </Button>
                </div>
              </div>

              <p className="text-sm text-muted-foreground dark:text-neutral-400">
                You can also deploy using your own workflow.
              </p>
            </div>
          </div>
        </div>
      );
    }

    return (
      <div className="bg-neutral-100 dark:bg-[#333] rounded-lg p-6">
        <div className="flex gap-9">
          {/* Preview Image */}
          <div className="shrink-0 w-[405px] h-[304px] bg-neutral-200 dark:bg-[#f8f8f7] rounded overflow-hidden">
            {deploymentUrl ? (
              <a
                href={deploymentUrl}
                target="_blank"
                rel="noopener noreferrer"
                className="block w-full h-full relative cursor-pointer hover:opacity-90 transition-opacity"
              >
                <iframe
                  key={iframeKey}
                  src={deploymentUrl}
                  title="Site Preview"
                  className="absolute top-0 left-0 w-[1215px] h-[912px] origin-top-left scale-[0.333] border-0 pointer-events-none"
                  sandbox="allow-scripts allow-same-origin"
                  loading="lazy"
                />
              </a>
            ) : (
              <div className="w-full h-full flex items-center justify-center text-muted-foreground text-sm">
                No preview available
              </div>
            )}
          </div>

          {/* Metadata Grid */}
          <div className="flex-1 flex flex-col gap-6 justify-center">
            <div className="flex flex-col">
              <p className="text-sm text-muted-foreground dark:text-neutral-400 leading-6">
                Deployment ID
              </p>
              <p className="text-sm text-zinc-950 dark:text-white font-mono">
                {latestReadyDeployment.id}
              </p>
            </div>

            <div className="grid grid-cols-2 gap-x-9">
              <div className="flex flex-col">
                <p className="text-sm text-muted-foreground dark:text-neutral-400 leading-6">
                  Status
                </p>
                <div>
                  <span
                    className={`inline-flex items-center justify-center h-5 px-2 rounded text-xs font-medium text-white ${statusColor}`}
                  >
                    {latestReadyDeployment.status === 'READY'
                      ? 'Ready'
                      : latestReadyDeployment.status}
                  </span>
                </div>
              </div>

              <div className="flex flex-col">
                <p className="text-sm text-muted-foreground dark:text-neutral-400 leading-6">
                  Provider
                </p>
                <p className="text-sm text-zinc-950 dark:text-white capitalize">
                  {latestReadyDeployment.provider}
                </p>
              </div>
            </div>

            <div className="flex flex-col">
              <p className="text-sm text-muted-foreground dark:text-neutral-400 leading-6">
                Created at
              </p>
              <p className="text-sm text-zinc-950 dark:text-white">
                {formatTime(latestReadyDeployment.createdAt)}
              </p>
            </div>

            <div className="flex flex-col gap-1">
              <p className="text-sm text-muted-foreground dark:text-neutral-400 leading-6">
                Domains
              </p>
              <div className="flex flex-col gap-1">
                {visibleDomains.length > 0
                  ? visibleDomains.map((domain) => (
                      <a
                        key={domain.href}
                        href={domain.href}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="text-sm text-zinc-950 dark:text-white hover:text-blue-600 dark:hover:text-blue-400 flex items-center gap-1"
                      >
                        {domain.label}
                        <ExternalLink className="w-3 h-3" />
                      </a>
                    ))
                  : null}
                {visibleDomains.length === 0 && (
                  <p className="text-sm text-zinc-950 dark:text-white">—</p>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  };

  return (
    <div className="h-full flex flex-col overflow-hidden bg-[rgb(var(--semantic-1))]">
      <div className="flex-1 min-h-0 overflow-auto p-6">
        <div className="w-full max-w-[1080px] mx-auto flex flex-col gap-6">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <h1 className="text-xl font-semibold text-zinc-950 dark:text-white">Overview</h1>
              <div className="h-6 w-px bg-gray-200 dark:bg-neutral-700" />
              <TooltipProvider>
                <Tooltip>
                  <TooltipTrigger asChild>
                    <Button
                      variant="ghost"
                      size="icon"
                      className="h-9 w-9 p-1"
                      onClick={() => void handleRefresh()}
                      disabled={isLoadingDeployments || isRefreshing}
                    >
                      <RefreshCw
                        className={cn(
                          'h-5 w-5 text-zinc-400 dark:text-neutral-400',
                          isRefreshing && 'animate-spin'
                        )}
                      />
                    </Button>
                  </TooltipTrigger>
                  <TooltipContent side="bottom">
                    <p>{isRefreshing ? 'Refreshing...' : 'Refresh'}</p>
                  </TooltipContent>
                </Tooltip>
              </TooltipProvider>
            </div>
            {primaryVisitUrl && (
              <Button
                asChild
                className="h-9 px-8 bg-zinc-950 text-white hover:bg-zinc-800 dark:bg-emerald-300 dark:text-zinc-950 dark:hover:bg-emerald-400"
              >
                <a href={primaryVisitUrl} target="_blank" rel="noopener noreferrer">
                  Visit
                </a>
              </Button>
            )}
          </div>
          {renderContent()}
        </div>
      </div>
    </div>
  );
}
