"use client";

import { useMemo, useState } from "react";
import Link from "next/link";
import {
  CheckCircle2,
  ExternalLink,
  Palette,
  RefreshCw,
  Shield,
  Sparkles,
  Upload,
} from "lucide-react";
import { analyzeWebsiteAesthetics } from "@/lib/website-aesthetic-analysis";
import { isWordPressConnected } from "@/lib/integrations/wordpress";
import {
  publishWebsiteHostDraft,
  resolveWebsiteHost,
  uploadWebsiteAestheticToHost,
} from "@/lib/website-host-upload";
import { saveBusiness } from "@/lib/data-store";
import type { Business, WebsiteAestheticAnalysis, WebsiteAestheticUploadReceipt } from "@/lib/types";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { ScoreRing } from "@/components/ui/score-ring";

const priorityStyles = {
  high: "border-amber-500/30 bg-amber-500/10 text-amber-300",
  medium: "border-sky-500/30 bg-sky-500/10 text-sky-300",
  low: "border-slate-700 bg-slate-800/50 text-slate-400",
};

const uploadStatusStyles = {
  draft_saved: "border-sky-500/30 bg-sky-500/10 text-sky-300",
  pending_approval: "border-amber-500/30 bg-amber-500/10 text-amber-300",
  published: "border-emerald-500/30 bg-emerald-500/10 text-emerald-300",
};

interface WebsiteAestheticPanelProps {
  business: Business;
  onUpdate?: (business: Business) => void;
  variant?: "compact" | "full";
}

export function WebsiteAestheticPanel({ business, onUpdate, variant = "full" }: WebsiteAestheticPanelProps) {
  const [analysis, setAnalysis] = useState<WebsiteAestheticAnalysis | null>(
    business.websiteAestheticAnalysis ?? null,
  );
  const [lastUpload, setLastUpload] = useState<WebsiteAestheticUploadReceipt | null>(
    business.websiteAestheticAnalysis?.lastHostUpload ?? null,
  );
  const [running, setRunning] = useState(false);
  const [uploading, setUploading] = useState<string | null>(null);
  const [expandedPayload, setExpandedPayload] = useState<string | null>(null);

  const host = useMemo(() => resolveWebsiteHost(business), [business]);
  const wpConnected = isWordPressConnected(business.integrations?.wordpress);

  const persist = async (next: Business) => {
    await saveBusiness(next);
    onUpdate?.(next);
  };

  const runAnalysis = async () => {
    setRunning(true);
    try {
      const result = analyzeWebsiteAesthetics(business);
      const next = {
        ...business,
        websiteAestheticAnalysis: result,
        updatedAt: new Date().toISOString(),
      };
      setAnalysis(result);
      setLastUpload(result.lastHostUpload ?? null);
      await persist(next);
    } finally {
      setRunning(false);
    }
  };

  const uploadToHost = async (recommendationIds?: string[]) => {
    setUploading(recommendationIds?.[0] ?? "all");
    try {
      const current = { ...business, websiteAestheticAnalysis: analysis ?? business.websiteAestheticAnalysis };
      const { receipt, business: next } = uploadWebsiteAestheticToHost(current, { recommendationIds });
      setLastUpload(receipt);
      setAnalysis(next.websiteAestheticAnalysis ?? null);
      await persist(next);
    } catch (error) {
      alert(error instanceof Error ? error.message : "Upload failed");
    } finally {
      setUploading(null);
    }
  };

  const approvePublish = async () => {
    setUploading("publish");
    try {
      const current = { ...business, websiteAestheticAnalysis: analysis ?? business.websiteAestheticAnalysis };
      const { receipt, business: next } = publishWebsiteHostDraft(current);
      setLastUpload(receipt);
      setAnalysis(next.websiteAestheticAnalysis ?? null);
      await persist(next);
    } catch (error) {
      alert(error instanceof Error ? error.message : "Publish failed");
    } finally {
      setUploading(null);
    }
  };

  const uploadedIds = new Set(lastUpload?.items.map((i) => i.recommendationId) ?? []);

  if (variant === "compact" && !analysis) {
    return (
      <Card className="border-violet-500/20">
        <CardHeader className="pb-2">
          <CardTitle className="flex items-center gap-2 text-sm">
            <Palette className="h-4 w-4 text-violet-400" />
            Website aesthetic analysis
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-3 text-sm">
          <p className="text-slate-400">
            Compare your site to top sellers in {business.input.industry}, then upload updates to {host?.name ?? "your host"}.
          </p>
          <Button size="sm" className="gap-2" onClick={runAnalysis} disabled={running}>
            <Sparkles className="h-3.5 w-3.5" />
            {running ? "Analyzing…" : "Analyze website"}
          </Button>
        </CardContent>
      </Card>
    );
  }

  if (variant === "compact" && analysis) {
    const topRec = analysis.recommendations.find((r) => r.priority === "high");
    return (
      <Card className="border-violet-500/20">
        <CardHeader className="pb-2">
          <CardTitle className="flex items-center justify-between gap-2 text-sm">
            <span className="flex items-center gap-2">
              <Palette className="h-4 w-4 text-violet-400" />
              Website aesthetic score
            </span>
            <ScoreRing score={analysis.overallScore} size={48} />
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-2 text-xs">
          <p className="text-slate-400">{analysis.executiveSummary.slice(0, 140)}…</p>
          {topRec ? (
            <p className="rounded-lg border border-slate-800 p-2 text-slate-300">
              <span className="text-amber-300">Top fix:</span> {topRec.title}
            </p>
          ) : null}
          {lastUpload ? (
            <Badge className={uploadStatusStyles[lastUpload.status]}>
              {lastUpload.status === "published" ? "Live on host" : "Draft on host"}
            </Badge>
          ) : null}
          <div className="flex flex-wrap gap-2">
            <Button
              size="sm"
              variant="outline"
              className="gap-1.5"
              onClick={() => uploadToHost()}
              disabled={!!uploading}
            >
              <Upload className="h-3 w-3" />
              {uploading ? "Uploading…" : `Upload to ${host?.name ?? "host"}`}
            </Button>
            <a href="/profile#website-analysis" className="self-center text-sky-400 hover:text-sky-300">
              Full analysis →
            </a>
          </div>
        </CardContent>
      </Card>
    );
  }

  return (
    <Card id="website-analysis" className="scroll-mt-6 border-violet-500/20">
      <CardHeader>
        <div className="flex flex-wrap items-start justify-between gap-4">
          <div>
            <CardTitle className="flex items-center gap-2">
              <Palette className="h-5 w-5 text-violet-400" />
              Website aesthetic analysis
            </CardTitle>
            <p className="mt-1 text-sm text-slate-400">
              Benchmarks your site against top-selling {business.input.industry} businesses, then uploads aesthetic updates to your website host while preserving your brand.
            </p>
          </div>
          <div className="flex flex-wrap gap-2 shrink-0">
            {analysis && host ? (
              <Button
                variant="outline"
                className="gap-2"
                onClick={() => uploadToHost()}
                disabled={!!uploading || !!running}
              >
                <Upload className="h-4 w-4" />
                {uploading === "all" ? "Uploading…" : `Upload to ${host.name}`}
              </Button>
            ) : null}
            <Button className="gap-2" onClick={runAnalysis} disabled={running}>
              {running ? (
                <>
                  <RefreshCw className="h-4 w-4 animate-spin" />
                  Analyzing…
                </>
              ) : analysis ? (
                <>
                  <RefreshCw className="h-4 w-4" />
                  Re-run analysis
                </>
              ) : (
                <>
                  <Sparkles className="h-4 w-4" />
                  Analyze website
                </>
              )}
            </Button>
          </div>
        </div>
      </CardHeader>
      <CardContent className="space-y-6">
        {host ? (
          <div className="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-slate-800 bg-slate-900/50 p-4">
            <div>
              <p className="text-xs uppercase text-slate-500">Connected website host</p>
              <p className="mt-1 font-medium text-slate-100">{host.name} · {host.category}</p>
              <p className="text-xs text-slate-500">{host.websiteUrl}</p>
              {host.name === "WordPress" && !wpConnected ? (
                <Link href="/settings#wordpress-api" className="mt-2 inline-block text-sm text-amber-300 hover:text-amber-200">
                  Connect WordPress API in Settings →
                </Link>
              ) : null}
              {wpConnected ? (
                <Badge className="mt-2 border-emerald-500/30 bg-emerald-500/10 text-emerald-300">Live API connected</Badge>
              ) : host.mode === "demo" ? (
                <Badge className="mt-2 border-slate-700 bg-slate-800/50 text-slate-400">Demo — connect API for live uploads</Badge>
              ) : null}
            </div>
            <Link
              href={host.adminUrl}
              target="_blank"
              rel="noopener noreferrer"
              className="inline-flex items-center gap-1.5 text-sm text-sky-400 hover:text-sky-300"
            >
              Open {host.name}
              <ExternalLink className="h-3.5 w-3.5" />
            </Link>
          </div>
        ) : null}

        {!analysis ? (
          <div className="rounded-xl border border-dashed border-slate-700 p-8 text-center text-sm text-slate-400">
            Run analysis to score your site vs industry leaders, then upload recommended aesthetic changes as drafts on {host?.name ?? "your CMS"}.
          </div>
        ) : (
          <>
            <div className="grid gap-4 md:grid-cols-[140px_1fr]">
              <div className="flex flex-col items-center gap-3">
                <ScoreRing score={analysis.overallScore} label="Your site" />
                <p className="text-center text-xs text-slate-500">
                  Industry leaders avg {analysis.industryBenchmarkScore}/100
                </p>
              </div>
              <div className="space-y-3">
                <p className="text-sm text-slate-300">{analysis.executiveSummary}</p>
                {analysis.websiteUrl ? (
                  <a
                    href={analysis.websiteUrl}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="inline-flex items-center gap-1.5 text-sm text-sky-300 hover:text-sky-200"
                  >
                    {analysis.websiteUrl}
                    <ExternalLink className="h-3.5 w-3.5" />
                  </a>
                ) : null}
                <div className="flex flex-wrap gap-2">
                  <Badge className="border-violet-500/30 bg-violet-500/10 text-violet-300">
                    Independence score: {analysis.independenceScore}/100
                  </Badge>
                  <Badge className="border-slate-700 bg-slate-800/50 text-slate-400">
                    Analyzed {new Date(analysis.analyzedAt).toLocaleDateString()}
                  </Badge>
                </div>
              </div>
            </div>

            {lastUpload ? (
              <div className="rounded-xl border border-sky-500/20 bg-sky-500/5 p-4">
                <div className="flex flex-wrap items-start justify-between gap-3">
                  <div>
                    <p className="flex items-center gap-2 font-medium text-slate-100">
                      <CheckCircle2 className="h-4 w-4 text-sky-400" />
                      Host upload receipt
                    </p>
                    <p className="mt-1 text-sm text-slate-400">{lastUpload.summary}</p>
                    <p className="mt-2 text-xs text-slate-500">{lastUpload.approvalNote}</p>
                  </div>
                  <Badge className={uploadStatusStyles[lastUpload.status]}>
                    {lastUpload.status === "published" ? "Published" : "Draft saved"}
                  </Badge>
                </div>
                <div className="mt-3 flex flex-wrap gap-2">
                  {lastUpload.previewUrl ? (
                    <Link
                      href={lastUpload.previewUrl}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="inline-flex items-center gap-1.5 text-xs text-sky-400 hover:text-sky-300"
                    >
                      {lastUpload.status === "published" ? "View live site" : "Open draft in CMS"}
                      <ExternalLink className="h-3 w-3" />
                    </Link>
                  ) : null}
                  {lastUpload.status === "draft_saved" ? (
                    <Button
                      size="sm"
                      className="gap-1.5"
                      onClick={approvePublish}
                      disabled={uploading === "publish"}
                    >
                      {uploading === "publish" ? "Publishing…" : "Approve & publish to host"}
                    </Button>
                  ) : null}
                </div>
                <div className="mt-3 space-y-2">
                  {lastUpload.items.map((item) => (
                    <div key={item.recommendationId} className="rounded-lg border border-slate-800 p-3 text-xs">
                      <p className="font-medium text-slate-200">{item.title}</p>
                      <p className="text-slate-500">{item.cmsAction} · {item.targetSection}</p>
                      <button
                        type="button"
                        className="mt-1 text-sky-400 hover:text-sky-300"
                        onClick={() =>
                          setExpandedPayload(
                            expandedPayload === item.recommendationId ? null : item.recommendationId,
                          )
                        }
                      >
                        {expandedPayload === item.recommendationId ? "Hide payload" : "View CMS payload"}
                      </button>
                      {expandedPayload === item.recommendationId ? (
                        <pre className="mt-2 max-h-40 overflow-auto rounded-md bg-slate-950 p-2 text-[11px] text-slate-400">
                          {item.payload}
                        </pre>
                      ) : null}
                    </div>
                  ))}
                </div>
              </div>
            ) : null}

            <div>
              <p className="mb-2 flex items-center gap-2 text-xs uppercase text-slate-500">
                <Shield className="h-3.5 w-3.5" />
                Keep your independence
              </p>
              <ul className="space-y-1.5 text-sm text-slate-300">
                {analysis.identityAnchors.map((anchor) => (
                  <li key={anchor} className="rounded-lg border border-emerald-500/20 bg-emerald-500/5 px-3 py-2">
                    {anchor}
                  </li>
                ))}
              </ul>
            </div>

            <div>
              <p className="mb-2 text-xs uppercase text-slate-500">What top sellers in {analysis.benchmark.industryLabel} do</p>
              <ul className="grid gap-2 sm:grid-cols-2">
                {analysis.benchmark.topPerformerTraits.map((trait) => (
                  <li key={trait} className="rounded-lg border border-slate-800 px-3 py-2 text-sm text-slate-400">
                    {trait}
                  </li>
                ))}
              </ul>
            </div>

            <div>
              <p className="mb-2 text-xs uppercase text-slate-500">Dimension scores</p>
              <div className="space-y-2">
                {analysis.dimensions.map((dim) => (
                  <div key={dim.dimension} className="rounded-xl border border-slate-800 p-3">
                    <div className="flex flex-wrap items-center justify-between gap-2">
                      <p className="font-medium text-slate-200">{dim.label}</p>
                      <div className="flex items-center gap-3 text-xs">
                        <span className="text-slate-400">You: {dim.yourScore}</span>
                        <span className="text-sky-400">Leaders: {dim.topPerformerAvg}</span>
                        {dim.gap > 0 ? (
                          <Badge className="border-amber-500/30 bg-amber-500/10 text-amber-300">−{dim.gap} gap</Badge>
                        ) : (
                          <Badge className="border-emerald-500/30 bg-emerald-500/10 text-emerald-300">On par</Badge>
                        )}
                      </div>
                    </div>
                    <div className="mt-2 grid gap-2 text-xs sm:grid-cols-2">
                      <p className="text-slate-500"><span className="text-slate-400">Your site:</span> {dim.yourNote}</p>
                      <p className="text-slate-500"><span className="text-sky-400">Top performers:</span> {dim.topPerformerNote}</p>
                    </div>
                  </div>
                ))}
              </div>
            </div>

            <div>
              <p className="mb-2 text-xs uppercase text-slate-500">Recommended updates (patterns, not clones)</p>
              <div className="space-y-3">
                {analysis.recommendations.map((rec) => (
                  <div key={rec.id} className="rounded-xl border border-slate-800 p-4">
                    <div className="flex flex-wrap items-center justify-between gap-2">
                      <div className="flex flex-wrap items-center gap-2">
                        <Badge className={priorityStyles[rec.priority]}>{rec.priority}</Badge>
                        {uploadedIds.has(rec.id) ? (
                          <Badge className="border-emerald-500/30 bg-emerald-500/10 text-emerald-300">On host</Badge>
                        ) : null}
                        <p className="font-medium text-slate-100">{rec.title}</p>
                      </div>
                      {rec.category !== "identity" && host ? (
                        <Button
                          size="sm"
                          variant="outline"
                          className="gap-1.5"
                          onClick={() => uploadToHost([rec.id])}
                          disabled={!!uploading}
                        >
                          <Upload className="h-3.5 w-3.5" />
                          {uploading === rec.id ? "Uploading…" : `Push to ${host.name}`}
                        </Button>
                      ) : null}
                    </div>
                    <p className="mt-2 text-sm text-slate-300">{rec.action}</p>
                    <div className="mt-3 grid gap-2 sm:grid-cols-2">
                      <div className="rounded-lg border border-sky-500/20 bg-sky-500/5 p-3 text-xs">
                        <p className="font-medium text-sky-300">Industry pattern</p>
                        <p className="mt-1 text-slate-400">{rec.industryPattern}</p>
                      </div>
                      <div className="rounded-lg border border-emerald-500/20 bg-emerald-500/5 p-3 text-xs">
                        <p className="font-medium text-emerald-300">Preserve independence</p>
                        <p className="mt-1 text-slate-400">{rec.preserveIndependence}</p>
                      </div>
                    </div>
                    <p className="mt-2 text-xs text-amber-300">Estimated impact: {rec.estimatedImpact}</p>
                  </div>
                ))}
              </div>
            </div>
          </>
        )}
      </CardContent>
    </Card>
  );
}
