"use client";

import ProductThumb from "@/components/app/product-thumb";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { countryNameFromIso2 } from "@/lib/iso-3166";
import { displaySourceLabel } from "@/lib/referrer-host";
import WorldVisitMap from "./world-visit-map";
import type {
  CityRow,
  CountryMapRow,
  Product,
  ProductAnalyticsOverview,
  ProductQueryRow,
} from "./types";

type Props = {
  analyticsFrom: string;
  analyticsTo: string;
  querySearch: string;
  analyticsLoading: boolean;
  analyticsOverview: ProductAnalyticsOverview | null;
  countryRows: CountryMapRow[];
  cityRows: CityRow[];
  queryRows: ProductQueryRow[];
  products: Product[];
  onFromChange: (value: string) => void;
  onToChange: (value: string) => void;
  onQuerySearchChange: (value: string) => void;
  onPreset: (days: number) => void;
  onApply: () => void;
};

const CHANNEL_LABELS: Record<string, string> = {
  direct: "Direct",
  organic: "Organic search",
  social: "Social",
  referral: "Referral",
  email: "Email",
  paid: "Paid",
  other: "Other",
};

export default function ProductAnalyticsTab({
  analyticsFrom,
  analyticsTo,
  querySearch,
  analyticsLoading,
  analyticsOverview,
  countryRows,
  cityRows,
  queryRows,
  products,
  onFromChange,
  onToChange,
  onQuerySearchChange,
  onPreset,
  onApply,
}: Props) {
  const sourceTotal = (analyticsOverview?.topSources || []).reduce((sum, row) => sum + (row.count || 0), 0);
  const topProductsByViews = [...products]
    .sort(
      (a, b) =>
        (b.popularityScore || 0) - (a.popularityScore || 0) || (b.viewsTotal || 0) - (a.viewsTotal || 0),
    )
    .slice(0, 15);

  return (
    <div className="space-y-4">
      <div className="grid gap-3 rounded-lg border bg-white p-4 md:grid-cols-6">
        <div className="grid gap-1">
          <Label>From</Label>
          <Input type="date" value={analyticsFrom} onChange={(e) => onFromChange(e.target.value)} />
        </div>
        <div className="grid gap-1">
          <Label>To</Label>
          <Input type="date" value={analyticsTo} onChange={(e) => onToChange(e.target.value)} />
        </div>
        <div className="grid gap-1 md:col-span-2">
          <Label>Search queries</Label>
          <Input
            value={querySearch}
            onChange={(e) => onQuerySearchChange(e.target.value)}
            placeholder="Filter queries…"
          />
        </div>
        <div className="flex flex-wrap items-end gap-2 md:col-span-2">
          <Button type="button" variant="outline" size="sm" onClick={() => onPreset(7)}>
            7d
          </Button>
          <Button type="button" variant="outline" size="sm" onClick={() => onPreset(30)}>
            30d
          </Button>
          <Button type="button" variant="outline" size="sm" onClick={() => onPreset(90)}>
            90d
          </Button>
          <Button className="ml-auto" onClick={onApply} disabled={analyticsLoading}>
            {analyticsLoading ? "Loading…" : "Apply"}
          </Button>
        </div>
      </div>

      <div className="grid gap-4 md:grid-cols-3">
        <Card className="shadow-none">
          <CardContent className="p-4">
            <p className="text-xs font-medium uppercase tracking-wide text-slate-500">Product views</p>
            <p className="mt-1 text-2xl font-semibold">{analyticsOverview?.viewsTotal || 0}</p>
          </CardContent>
        </Card>
        <Card className="shadow-none">
          <CardContent className="p-4">
            <p className="text-xs font-medium uppercase tracking-wide text-slate-500">Unique visitors</p>
            <p className="mt-1 text-2xl font-semibold">{analyticsOverview?.uniqueVisitorsTotal || 0}</p>
          </CardContent>
        </Card>
        <Card className="shadow-none">
          <CardContent className="p-4">
            <p className="text-xs font-medium uppercase tracking-wide text-slate-500">Avg. time on page</p>
            <p className="mt-1 text-2xl font-semibold">{analyticsOverview?.avgReadTimeSec || 0}s</p>
          </CardContent>
        </Card>
      </div>

      <div className="grid gap-4 lg:grid-cols-3">
        <Card className="shadow-none lg:col-span-2">
          <CardContent className="p-4">
            <p className="mb-3 text-sm font-semibold text-slate-800">Visitor map</p>
            <WorldVisitMap countryRows={countryRows} />
          </CardContent>
        </Card>

        <div className="space-y-4">
          <Card className="shadow-none">
            <CardContent className="p-4">
              <p className="mb-3 text-sm font-semibold text-slate-800">Traffic channels</p>
              {(analyticsOverview?.topSources || []).length === 0 ? (
                <p className="text-sm text-slate-500">No source data in this range.</p>
              ) : (
                <div className="space-y-2">
                  {(analyticsOverview?.topSources || []).map((row) => {
                    const pct = sourceTotal > 0 ? Math.round((row.count / sourceTotal) * 100) : 0;
                    return (
                      <div key={row.source}>
                        <div className="mb-1 flex items-center justify-between text-sm">
                          <span className="text-slate-700">
                            {CHANNEL_LABELS[row.source] || row.source}
                          </span>
                          <span className="font-medium text-slate-900">
                            {row.count} · {pct}%
                          </span>
                        </div>
                        <div className="h-1.5 overflow-hidden rounded-full bg-slate-100">
                          <div className="h-full rounded-full bg-teal-600" style={{ width: `${pct}%` }} />
                        </div>
                      </div>
                    );
                  })}
                </div>
              )}
            </CardContent>
          </Card>

          <Card className="shadow-none">
            <CardContent className="p-4">
              <p className="mb-3 text-sm font-semibold text-slate-800">Traffic sources</p>
              {(analyticsOverview?.topSourceDetails || []).length === 0 ? (
                <p className="text-sm text-slate-500">No referrer or UTM sources yet.</p>
              ) : (
                <div className="space-y-2">
                  {(analyticsOverview?.topSourceDetails || []).map((row) => (
                    <div
                      key={`${row.label}-${row.channel}`}
                      className="flex items-center justify-between rounded-md border px-3 py-2"
                    >
                      <div className="min-w-0">
                        <p className="truncate text-sm font-medium text-slate-800">
                          {displaySourceLabel(row.label)}
                        </p>
                        <p className="text-xs capitalize text-slate-400">
                          {CHANNEL_LABELS[row.channel] || row.channel}
                        </p>
                      </div>
                      <span className="text-sm font-semibold">{row.count}</span>
                    </div>
                  ))}
                </div>
              )}
            </CardContent>
          </Card>
        </div>
      </div>

      <div className="grid gap-4 lg:grid-cols-3">
        <Card className="shadow-none">
          <CardContent className="p-4">
            <p className="mb-3 text-sm font-semibold text-slate-800">Top cities (Pakistan)</p>
            <div className="space-y-2">
              {cityRows.length === 0 ? (
                <p className="text-sm text-slate-500">No Pakistan city data available.</p>
              ) : (
                cityRows.map((row) => (
                  <div key={row.city} className="flex items-center justify-between rounded-md border px-3 py-2">
                    <span className="text-sm">{row.city}</span>
                    <span className="text-sm font-semibold">{row.visits}</span>
                  </div>
                ))
              )}
            </div>
          </CardContent>
        </Card>

        <Card className="shadow-none">
          <CardContent className="p-4">
            <p className="mb-3 text-sm font-semibold text-slate-800">Top countries</p>
            <div className="space-y-2">
              {countryRows.length === 0 ? (
                <p className="text-sm text-slate-500">No country data available.</p>
              ) : (
                countryRows.map((row) => (
                  <div
                    key={`${row.countryCode}-${row.country}`}
                    className="flex items-center justify-between rounded-md border px-3 py-2"
                  >
                    <span className="text-sm">
                      {countryNameFromIso2(row.countryCode, row.country)}
                    </span>
                    <span className="text-sm font-semibold">{row.visits}</span>
                  </div>
                ))
              )}
            </div>
          </CardContent>
        </Card>

        <Card className="shadow-none">
          <CardContent className="p-4">
            <p className="mb-3 text-sm font-semibold text-slate-800">Top search queries</p>
            <div className="max-h-[300px] space-y-2 overflow-auto">
              {queryRows.length === 0 ? (
                <p className="text-sm text-slate-500">No search queries in selected range.</p>
              ) : (
                queryRows.map((row) => (
                  <div key={`${row.query}-${row.lastSearchedAt || "na"}`} className="rounded-md border px-3 py-2">
                    <p className="text-sm font-medium">{row.query}</p>
                    <div className="mt-1 flex items-center justify-between text-xs text-slate-500">
                      <span>Searches: {row.searches}</span>
                      <span>Avg results: {row.avgResultCount}</span>
                    </div>
                  </div>
                ))
              )}
            </div>
          </CardContent>
        </Card>
      </div>

      <Card className="shadow-none">
        <CardContent className="p-4">
          <p className="mb-3 text-sm font-semibold text-slate-800">Products by popularity</p>
          <div className="space-y-2">
            {topProductsByViews.length === 0 ? (
              <p className="text-sm text-slate-500">No products yet.</p>
            ) : (
              topProductsByViews.map((p) => (
                <div key={p._id} className="flex items-center justify-between rounded-md border px-3 py-2">
                  <div className="flex min-w-0 max-w-[70%] items-center gap-2">
                    <ProductThumb src={p.images?.[0]} alt={p.title} />
                    <span className="truncate text-sm">{p.title}</span>
                  </div>
                  <span className="text-xs text-slate-500">
                    {p.viewsTotal || 0} views · score {p.popularityScore || 0}
                  </span>
                </div>
              ))
            )}
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
