"use client";

import { useState, useTransition } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { AlertCircle, ArrowRight, BarChart3, Radar, ShieldAlert, Sparkles } from "lucide-react";

import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import {
  competitorAnalysisSchema,
  sectorRequestSchema,
  type CompetitorAnalysis,
  type SectorRequest
} from "@/lib/schema";

const sampleAnalysis: CompetitorAnalysis = {
  sector_overview:
    "Plant-based protein foods remain a sizable but uneven category, with growth concentrating in formats that balance taste, nutrition, and everyday use. Buyers are more selective than they were during the category’s hype cycle, rewarding brands that can prove repeat purchase and margin discipline. The structural dynamic is that mainstream adoption depends on price, product quality, and retailer confidence all improving at the same time.",
  key_players: [
    {
      name: "Beyond Meat",
      positioning: "Category pioneer with strong awareness in retail and foodservice plant-based meat.",
      market_tier: "leader",
      key_weakness: "Sustained revenue pressure and uneven distribution have reduced its room for error."
    },
    {
      name: "Impossible Foods",
      positioning: "Technology-forward challenger focused on meat-like flavor and broad U.S. availability.",
      market_tier: "challenger",
      key_weakness: "It still contends with consumer skepticism around processed formulations."
    },
    {
      name: "Oatly",
      positioning: "Brand-led oat milk specialist with strong cafe and grocery recognition.",
      market_tier: "challenger",
      key_weakness: "Its tighter category focus limits coverage outside the dairy-alternative set."
    },
    {
      name: "Hodo",
      positioning: "Whole-food niche brand known for premium tofu and cleaner-label protein products.",
      market_tier: "niche",
      key_weakness: "Its narrower scale constrains mass-market reach."
    }
  ],
  emerging_trends: [
    {
      trend: "Clean-label reformulation",
      description:
        "Brands are simplifying ingredients and reducing sodium or saturated fat to counter ultra-processed perceptions. This is strongest where products still need to win over mainstream shoppers.",
      relevance_to_entrant: "A new entrant can build around this consumer expectation from the start.",
      confidence: "high"
    },
    {
      trend: "Flexitarian-first positioning",
      description:
        "Messaging is shifting away from ideology and toward taste, convenience, and protein. Buyers increasingly include mixed-diet households rather than only strict vegans.",
      relevance_to_entrant: "The easiest wedge is often a mainstream use case, not a niche identity segment.",
      confidence: "high"
    },
    {
      trend: "Retailers favor velocity over assortment breadth",
      description:
        "Shelf space is tightening, and weaker SKUs are being removed faster than before. Winning products need clearer differentiation and repeat demand.",
      relevance_to_entrant: "The GTM plan should be narrow, measurable, and retailer-friendly.",
      confidence: "medium"
    }
  ],
  white_spaces: [
    {
      opportunity: "Affordable clean-label center-of-plate proteins",
      rationale:
        "There is still room between highly processed analogs and premium whole-food specialists. A product that stays simple but delivers better texture and price can occupy that middle."
    },
    {
      opportunity: "Convenience-led refrigerated meal components",
      rationale:
        "Many buyers want easy weeknight formats rather than hero burgers alone. Strips, crumbles, snack packs, and deli-led formats better fit habitual consumption."
    }
  ],
  data_confidence: {
    overall_rating: "medium",
    flagged_uncertainties: [
      "Private-company market share is often opaque.",
      "Category growth rates vary materially by geography and subsegment."
    ]
  }
};

type ApiState = {
  analysis: CompetitorAnalysis | null;
  error: string | null;
};

function MarketTierBadge({ value }: { value: CompetitorAnalysis["key_players"][number]["market_tier"] }) {
  return (
    <span className="rounded-full border border-border bg-muted px-3 py-1 text-xs font-semibold uppercase tracking-[0.18em] text-muted-foreground">
      {value}
    </span>
  );
}

function ConfidenceBadge({ value }: { value: "high" | "medium" | "low" }) {
  return (
    <span className="rounded-full border border-border px-3 py-1 text-xs font-semibold uppercase tracking-[0.18em]">
      {value}
    </span>
  );
}

export function DashboardShell() {
  const [isPending, startTransition] = useTransition();
  const [apiState, setApiState] = useState<ApiState>({
    analysis: sampleAnalysis,
    error: null
  });

  const form = useForm<SectorRequest>({
    resolver: zodResolver(sectorRequestSchema),
    defaultValues: {
      sector: "",
      geography: "",
      customerType: "",
      focus: ""
    }
  });

  const onSubmit = form.handleSubmit((values) => {
    startTransition(async () => {
      setApiState((current) => ({ ...current, error: null }));

      try {
        const response = await fetch("/api/analyze", {
          method: "POST",
          headers: {
            "Content-Type": "application/json"
          },
          body: JSON.stringify(values)
        });

        const payload = await response.json();

        if (!response.ok) {
          throw new Error(payload.error || "Request failed.");
        }

        const analysis = competitorAnalysisSchema.parse(payload);
        setApiState({ analysis, error: null });
      } catch (error) {
        setApiState({
          analysis: null,
          error: error instanceof Error ? error.message : "Unexpected request error."
        });
      }
    });
  });

  return (
    <main className="min-h-screen">
      <div className="mx-auto flex w-full max-w-7xl flex-col gap-6 px-4 py-6 sm:px-6 lg:px-8 lg:py-8">
        <section className="grid gap-6 lg:grid-cols-[1.05fr_1.35fr]">
          <Card className="overflow-hidden border-black bg-black text-white">
            <CardHeader className="pb-4">
              <div className="mb-6 inline-flex w-fit rounded-full border border-white/20 px-3 py-1 text-xs uppercase tracking-[0.22em] text-white/70">
                Competitive Intelligence Engine
              </div>
              <CardTitle className="text-4xl leading-tight sm:text-5xl">
                Sector dashboard for fast competitor analysis.
              </CardTitle>
              <CardDescription className="max-w-xl text-base text-white/70">
                Submit a sector request and return structured market intelligence that matches your analysis schema.
              </CardDescription>
            </CardHeader>
            <CardContent className="grid gap-4 sm:grid-cols-3">
              <div className="rounded-3xl border border-white/10 bg-white/5 p-4">
                <BarChart3 className="mb-4 h-5 w-5" />
                <p className="text-sm text-white/70">Typed API contract and structured response rendering.</p>
              </div>
              <div className="rounded-3xl border border-white/10 bg-white/5 p-4">
                <Radar className="mb-4 h-5 w-5" />
                <p className="text-sm text-white/70">Mobile-first layout in a restrained black-and-white visual system.</p>
              </div>
              <div className="rounded-3xl border border-white/10 bg-white/5 p-4">
                <Sparkles className="mb-4 h-5 w-5" />
                <p className="text-sm text-white/70">Ready for a real LLM-backed analysis service behind the route.</p>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>Request Analysis</CardTitle>
              <CardDescription>
                Provide the target sector and optional commercial context for a sharper output.
              </CardDescription>
            </CardHeader>
            <CardContent>
              <form className="grid gap-4" onSubmit={onSubmit}>
                <div className="grid gap-2">
                  <label className="text-sm font-medium" htmlFor="sector">
                    Sector
                  </label>
                  <Input id="sector" placeholder="Plant-based protein food industry" {...form.register("sector")} />
                  {form.formState.errors.sector ? (
                    <p className="text-sm text-destructive">{form.formState.errors.sector.message}</p>
                  ) : null}
                </div>

                <div className="grid gap-4 sm:grid-cols-2">
                  <div className="grid gap-2">
                    <label className="text-sm font-medium" htmlFor="geography">
                      Geography
                    </label>
                    <Input id="geography" placeholder="United States" {...form.register("geography")} />
                  </div>
                  <div className="grid gap-2">
                    <label className="text-sm font-medium" htmlFor="customerType">
                      Customer Type
                    </label>
                    <Input id="customerType" placeholder="Retail grocery buyers" {...form.register("customerType")} />
                  </div>
                </div>

                <div className="grid gap-2">
                  <label className="text-sm font-medium" htmlFor="focus">
                    Strategic Focus
                  </label>
                  <Textarea
                    id="focus"
                    placeholder="Example: launch opportunities for a new entrant with cleaner-label positioning."
                    {...form.register("focus")}
                  />
                </div>

                <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                  <p className="text-sm text-muted-foreground">
                    Backend requests are validated locally and analyzed through the OpenAI API.
                  </p>
                  <Button className="w-full sm:w-auto" size="lg" type="submit" disabled={isPending}>
                    {isPending ? "Generating..." : "Generate Analysis"}
                    <ArrowRight className="ml-2 h-4 w-4" />
                  </Button>
                </div>
              </form>
            </CardContent>
          </Card>
        </section>

        {apiState.error ? (
          <Card className="border-destructive">
            <CardContent className="flex items-start gap-3 p-6">
              <AlertCircle className="mt-0.5 h-5 w-5 text-destructive" />
              <div>
                <p className="font-semibold">Request failed</p>
                <p className="text-sm text-muted-foreground">{apiState.error}</p>
              </div>
            </CardContent>
          </Card>
        ) : null}

        {apiState.analysis ? (
          <section className="grid gap-6">
            <div className="grid gap-6 xl:grid-cols-[1.15fr_0.85fr]">
              <Card>
                <CardHeader>
                  <CardTitle>Sector Overview</CardTitle>
                  <CardDescription>High-level market framing for the current request.</CardDescription>
                </CardHeader>
                <CardContent>
                  <p className="text-lg leading-8">{apiState.analysis.sector_overview}</p>
                </CardContent>
              </Card>

              <Card>
                <CardHeader>
                  <CardTitle>Data Confidence</CardTitle>
                  <CardDescription>Confidence signal and flagged risks to validate further.</CardDescription>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="flex items-center gap-3">
                    <ShieldAlert className="h-5 w-5" />
                    <div>
                      <p className="text-sm text-muted-foreground">Overall rating</p>
                      <p className="text-lg font-semibold uppercase">{apiState.analysis.data_confidence.overall_rating}</p>
                    </div>
                  </div>
                  <div className="space-y-3">
                    {apiState.analysis.data_confidence.flagged_uncertainties.map((item) => (
                      <div className="rounded-3xl border border-border bg-muted p-4" key={item}>
                        <p className="text-sm leading-6">{item}</p>
                      </div>
                    ))}
                  </div>
                </CardContent>
              </Card>
            </div>

            <Card>
              <CardHeader>
                <CardTitle>Key Players</CardTitle>
                <CardDescription>Competitive set grouped by positioning and key weakness.</CardDescription>
              </CardHeader>
              <CardContent className="grid gap-4 md:grid-cols-2">
                {apiState.analysis.key_players.map((player) => (
                  <div className="rounded-[1.25rem] border border-border bg-muted/50 p-5" key={player.name}>
                    <div className="mb-4 flex items-start justify-between gap-3">
                      <div>
                        <h3 className="font-[family-name:var(--font-heading)] text-xl font-semibold">
                          {player.name}
                        </h3>
                        <p className="mt-1 text-sm text-muted-foreground">{player.positioning}</p>
                      </div>
                      <MarketTierBadge value={player.market_tier} />
                    </div>
                    <div className="rounded-2xl border border-border bg-white p-4">
                      <p className="text-xs uppercase tracking-[0.18em] text-muted-foreground">
                        Key weakness
                      </p>
                      <p className="mt-2 text-sm leading-6">{player.key_weakness}</p>
                    </div>
                  </div>
                ))}
              </CardContent>
            </Card>

            <div className="grid gap-6 lg:grid-cols-2">
              <Card>
                <CardHeader>
                  <CardTitle>Emerging Trends</CardTitle>
                  <CardDescription>Signals that matter for market entry planning.</CardDescription>
                </CardHeader>
                <CardContent className="space-y-4">
                  {apiState.analysis.emerging_trends.map((trend) => (
                    <div className="rounded-[1.25rem] border border-border bg-muted/50 p-5" key={trend.trend}>
                      <div className="mb-3 flex items-center justify-between gap-3">
                        <h3 className="font-[family-name:var(--font-heading)] text-lg font-semibold">
                          {trend.trend}
                        </h3>
                        <ConfidenceBadge value={trend.confidence} />
                      </div>
                      <p className="text-sm leading-6 text-muted-foreground">{trend.description}</p>
                      <div className="mt-4 rounded-2xl border border-border bg-white p-4">
                        <p className="text-xs uppercase tracking-[0.18em] text-muted-foreground">
                          Relevance to entrant
                        </p>
                        <p className="mt-2 text-sm leading-6">{trend.relevance_to_entrant}</p>
                      </div>
                    </div>
                  ))}
                </CardContent>
              </Card>

              <Card>
                <CardHeader>
                  <CardTitle>White Spaces</CardTitle>
                  <CardDescription>Areas where a focused new entrant may have room to win.</CardDescription>
                </CardHeader>
                <CardContent className="space-y-4">
                  {apiState.analysis.white_spaces.map((space) => (
                    <div className="rounded-[1.25rem] border border-border bg-black p-5 text-white" key={space.opportunity}>
                      <h3 className="font-[family-name:var(--font-heading)] text-lg font-semibold">
                        {space.opportunity}
                      </h3>
                      <p className="mt-3 text-sm leading-6 text-white/75">{space.rationale}</p>
                    </div>
                  ))}
                </CardContent>
              </Card>
            </div>
          </section>
        ) : null}
      </div>
    </main>
  );
}
