"use client";

import { Check, RefreshCw } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { Textarea } from "@/components/ui/textarea";
import { Input } from "@/components/ui/input";
import type { BusinessContext, FactSource } from "@/types/workflow";
import { MISSING_FACT, UNKNOWN_FACT, isPresentFact } from "@/lib/context/facts";
import { STORYTELLING_FRAMEWORK } from "@/lib/context/storytelling-framework";
import { cn } from "@/lib/utils";

function sourceBadge(source?: FactSource) {
  if (source === "user") return "You";
  if (source === "website") return "Website";
  return "Needs review";
}

function linesToList(text: string): string[] {
  return text
    .split("\n")
    .map((s) => s.replace(/^[-•]\s*/, "").trim())
    .filter(Boolean);
}

function listToLines(items: string[]): string {
  return items.join("\n");
}

function FactValue({ value }: { value: string }) {
  const missing = !isPresentFact(value) || value === MISSING_FACT || value === UNKNOWN_FACT;
  return (
    <span className={missing ? "italic text-amber-700" : "text-gray-800"}>
      {missing ? value || MISSING_FACT : value}
    </span>
  );
}

export function BusinessContextPanel(props: {
  context: BusinessContext | undefined;
  analyzing?: boolean;
  onChange: (patch: Partial<BusinessContext>) => void;
  onRefresh: () => void;
  onConfirm: () => void;
}) {
  const ctx = props.context;
  const confirmed = Boolean(ctx?.confirmed);
  const fieldSources = ctx?.fieldSources ?? {};
  const contact = ctx?.contact ?? { phone: "", email: "", address: "" };

  return (
    <Card
      title="This is what we understand about your business"
      subtitle="Review and confirm before large-scale generation. Explicit edits you make here take priority over website scrape and inference."
    >
      {!ctx ? (
        <p className="text-sm text-gray-500">
          Add a website URL in My Project, then refresh to extract company facts. Nothing is
          invented if it is not found.
        </p>
      ) : (
        <div className="space-y-6">
          <div
            className={cn(
              "rounded-lg border px-3 py-2 text-xs",
              confirmed
                ? "border-green-200 bg-green-50 text-green-900"
                : "border-amber-200 bg-amber-50 text-amber-950",
            )}
          >
            {confirmed
              ? `Business context confirmed${ctx.confirmedAt ? ` ${new Date(ctx.confirmedAt).toLocaleString()}` : ""}. Generation will use this as the factual source of truth.`
              : "Not confirmed yet. Edit anything that is wrong, fill gaps, then confirm."}
          </div>

          <div className="grid gap-4 sm:grid-cols-2">
            <Input
              id="bc-company"
              label={`Company · ${sourceBadge(fieldSources.companyName)}`}
              value={isPresentFact(ctx.companyName) ? ctx.companyName : ""}
              placeholder="missing"
              onChange={(e) =>
                props.onChange({
                  companyName: e.target.value,
                  fieldSources: { ...fieldSources, companyName: "user" },
                })
              }
            />
            <Input
              id="bc-industry"
              label={`Industry · ${sourceBadge(fieldSources.industry)}`}
              value={isPresentFact(ctx.industry) ? ctx.industry : ""}
              placeholder="missing"
              onChange={(e) =>
                props.onChange({
                  industry: e.target.value,
                  fieldSources: { ...fieldSources, industry: "user" },
                })
              }
            />
            <div className="sm:col-span-2">
              <Textarea
                id="bc-description"
                label={`Description · ${sourceBadge(fieldSources.description)}`}
                rows={3}
                value={isPresentFact(ctx.description) ? ctx.description : ""}
                placeholder="missing — AI will not invent a company description"
                onChange={(e) =>
                  props.onChange({
                    description: e.target.value,
                    fieldSources: { ...fieldSources, description: "user" },
                  })
                }
              />
            </div>
            <div>
              <p className="text-xs font-medium uppercase tracking-wide text-gray-500">
                Phone · {sourceBadge(fieldSources.phone)}
              </p>
              <p className="mt-1 text-sm">
                <FactValue value={contact.phone} />
              </p>
            </div>
            <div>
              <p className="text-xs font-medium uppercase tracking-wide text-gray-500">
                Email · {sourceBadge(fieldSources.email)}
              </p>
              <p className="mt-1 text-sm">
                <FactValue value={contact.email} />
              </p>
            </div>
          </div>

          <div className="grid gap-4 lg:grid-cols-2">
            <Textarea
              id="bc-audience"
              label="Who you serve"
              rows={3}
              value={isPresentFact(ctx.audience) ? ctx.audience : ""}
              placeholder="Roles, industries, regions — your words override the website"
              onChange={(e) =>
                props.onChange({
                  audience: e.target.value,
                  fieldSources: { ...fieldSources, audience: "user" },
                })
              }
            />
            <Textarea
              id="bc-products"
              label="Products (one per line)"
              rows={3}
              value={listToLines(ctx.products)}
              placeholder="Leave blank if unknown — AI will not invent them"
              onChange={(e) => {
                const list = linesToList(e.target.value);
                props.onChange({
                  products: list,
                  fieldSources: { ...fieldSources, products: "user" },
                });
              }}
            />
            <Textarea
              id="bc-services"
              label="Services (one per line)"
              rows={3}
              value={listToLines(ctx.services)}
              placeholder="Leave blank if unknown — AI will not invent them"
              onChange={(e) => {
                const list = linesToList(e.target.value);
                props.onChange({
                  services: list,
                  fieldSources: { ...fieldSources, services: "user" },
                });
              }}
            />
            <Textarea
              id="bc-problems"
              label="Customer problems (one per line)"
              rows={3}
              value={listToLines(ctx.customerProblems)}
              placeholder="Real problems your customers face"
              onChange={(e) =>
                props.onChange({
                  customerProblems: linesToList(e.target.value),
                  fieldSources: { ...fieldSources, customerProblems: "user" },
                })
              }
            />
            <Textarea
              id="bc-pain"
              label="Pain points (one per line)"
              rows={3}
              value={listToLines(ctx.painPoints)}
              placeholder="Operational or emotional friction — leave blank if unknown"
              onChange={(e) =>
                props.onChange({
                  painPoints: linesToList(e.target.value),
                  fieldSources: { ...fieldSources, painPoints: "user" },
                })
              }
            />
            <Textarea
              id="bc-impact"
              label="Business impact (one per line)"
              rows={3}
              value={listToLines(ctx.businessImpact)}
              placeholder="What happens if the problem is ignored"
              onChange={(e) =>
                props.onChange({
                  businessImpact: linesToList(e.target.value),
                  fieldSources: { ...fieldSources, businessImpact: "user" },
                })
              }
            />
            <Textarea
              id="bc-diff"
              label="Differentiators"
              rows={3}
              value={listToLines(ctx.differentiators)}
              onChange={(e) =>
                props.onChange({
                  differentiators: linesToList(e.target.value),
                  fieldSources: { ...fieldSources, differentiators: "user" },
                })
              }
            />
            <Textarea
              id="bc-proof"
              label="Verified claims / proof"
              rows={3}
              value={listToLines(ctx.verifiedClaims)}
              placeholder="Only results you can stand behind. If empty, posts will use hypothetical language."
              onChange={(e) =>
                props.onChange({
                  verifiedClaims: linesToList(e.target.value),
                  fieldSources: { ...fieldSources, verifiedClaims: "user" },
                })
              }
            />
          </div>

          {(ctx.missingInformation ?? []).length > 0 && (
            <div className="rounded-lg border border-gray-200 bg-gray-50 px-3 py-2 text-xs text-gray-700">
              <p className="font-semibold text-gray-900">Missing information</p>
              <p className="mt-1">{(ctx.missingInformation ?? []).join(" · ")}</p>
              <p className="mt-1 text-gray-500">
                AI will not fill these with invented facts.
              </p>
            </div>
          )}

          <div>
            <p className="mb-2 text-sm font-semibold text-gray-900">
              Storytelling framework (structure only)
            </p>
            <p className="mb-3 text-xs text-gray-500">
              Your business is the subject. This framework only supplies narrative order — no
              fictional characters or novel text.
            </p>
            <ol className="grid gap-2 sm:grid-cols-2 lg:grid-cols-5">
              {STORYTELLING_FRAMEWORK.map((beat) => (
                <li
                  key={beat.role}
                  className="rounded-lg border border-gray-100 bg-gray-50 px-3 py-2 text-xs"
                >
                  <p className="font-semibold text-gray-900">
                    {beat.index + 1}. {beat.title}
                  </p>
                  <p className="mt-1 text-gray-500">{beat.customerMapping}</p>
                </li>
              ))}
            </ol>
          </div>

          <div className="flex flex-wrap gap-2">
            <Button type="button" variant="ghost" size="sm" onClick={props.onRefresh} disabled={props.analyzing}>
              <RefreshCw className={cn("h-4 w-4", props.analyzing && "animate-spin")} />
              {props.analyzing ? "Refreshing…" : "Rebuild from website + brand"}
            </Button>
            <Button type="button" variant="teal" size="sm" onClick={props.onConfirm} disabled={!ctx}>
              <Check className="h-4 w-4" />
              Confirm business context
            </Button>
          </div>
        </div>
      )}
    </Card>
  );
}

export function ContentStrategyFields(props: {
  themes: string;
  goals: string;
  sequenceStrategy: string;
  onChange: (patch: { themes?: string; goals?: string; sequenceStrategy?: string }) => void;
}) {
  return (
    <Card title="Content strategy" subtitle="Themes and goals for the connected sequence.">
      <div className="grid gap-4 lg:grid-cols-2">
        <Input
          id="strategy-themes"
          label="Content themes"
          placeholder="e.g. operational friction, buyer education"
          value={props.themes}
          onChange={(e) => props.onChange({ themes: e.target.value })}
        />
        <Input
          id="strategy-goals"
          label="Content goals"
          placeholder="e.g. educate, differentiate, invite a conversation"
          value={props.goals}
          onChange={(e) => props.onChange({ goals: e.target.value })}
        />
        <div className="lg:col-span-2">
          <Textarea
            id="strategy-sequence"
            label="Sequence strategy"
            rows={2}
            value={props.sequenceStrategy}
            onChange={(e) => props.onChange({ sequenceStrategy: e.target.value })}
          />
        </div>
      </div>
    </Card>
  );
}
