"use client";

import { useState, useEffect, useCallback } from "react";
import { Loader2, Save, SlidersHorizontal, X } from "lucide-react";
import { toast } from "sonner";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Checkbox } from "@/components/ui/checkbox";
import { Label } from "@/components/ui/label";
import { PageHeader } from '@/components/navigation/page-header';

interface CompanyCategory {
  value: number;
  label: string;
  is_active: boolean;
}

interface Company {
  id: number;
  company_name: string;
}

interface SectionSettings {
  company_category_ids: number[];
  excluded_company_ids: number[];
}

interface DisplaySettings {
  kiosk: SectionSettings;
  mobile: SectionSettings;
}

function CompanySearch({
  selectedIds,
  categoryIds,
  onAdd,
  onRemove,
  allCompanies,
}: {
  selectedIds: number[];
  categoryIds: number[];
  onAdd: (id: number) => void;
  onRemove: (id: number) => void;
  allCompanies: Company[];
}) {
  const [query, setQuery] = useState("");
  const [open, setOpen] = useState(false);

  const available = allCompanies.filter(
    (c) =>
      !selectedIds.includes(c.id) &&
      (query === "" || c.company_name.toLowerCase().includes(query.toLowerCase()))
  );

  const selected = allCompanies.filter((c) => selectedIds.includes(c.id));

  return (
    <div className="space-y-2">
      <div className="flex flex-wrap gap-1 min-h-[28px]">
        {selected.map((c) => (
          <Badge key={c.id} variant="secondary" className="gap-1">
            {c.company_name}
            <button
              onClick={() => onRemove(c.id)}
              className="ml-1 hover:text-destructive"
              aria-label={`Remove ${c.company_name}`}
            >
              <X className="h-3 w-3" />
            </button>
          </Badge>
        ))}
        {selected.length === 0 && (
          <span className="text-xs text-muted-foreground italic">No exclusions</span>
        )}
      </div>
      <div className="relative">
        <input
          type="text"
          placeholder="Search companies to exclude..."
          value={query}
          onChange={(e) => { setQuery(e.target.value); setOpen(true); }}
          onFocus={() => setOpen(true)}
          onBlur={() => setTimeout(() => setOpen(false), 150)}
          className="w-full rounded-md border border-input bg-background px-3 py-1.5 text-sm shadow-sm placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring"
        />
        {open && available.length > 0 && (
          <div className="absolute z-50 mt-1 w-full max-h-52 overflow-auto rounded-md border bg-popover shadow-md">
            {available.slice(0, 30).map((c) => (
              <button
                key={c.id}
                className="w-full px-3 py-2 text-left text-sm hover:bg-accent hover:text-accent-foreground"
                onMouseDown={() => { onAdd(c.id); setQuery(""); }}
              >
                {c.company_name}
                <span className="ml-2 text-xs text-muted-foreground">#{c.id}</span>
              </button>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

function Section({
  title,
  description,
  settingsKey,
  settings,
  categories,
  companies,
  onSaved,
}: {
  title: string;
  description: string;
  settingsKey: "kiosk" | "mobile";
  settings: SectionSettings;
  categories: CompanyCategory[];
  companies: Company[];
  onSaved: (key: "kiosk" | "mobile", updated: SectionSettings) => void;
}) {
  const [local, setLocal] = useState<SectionSettings>(settings);
  const [saving, setSaving] = useState(false);

  useEffect(() => { setLocal(settings); }, [settings]);

  function toggleCategory(value: number) {
    setLocal((prev) => ({
      ...prev,
      company_category_ids: prev.company_category_ids.includes(value)
        ? prev.company_category_ids.filter((v) => v !== value)
        : [...prev.company_category_ids, value],
    }));
  }

  function addExclusion(id: number) {
    setLocal((prev) => ({ ...prev, excluded_company_ids: [...prev.excluded_company_ids, id] }));
  }

  function removeExclusion(id: number) {
    setLocal((prev) => ({ ...prev, excluded_company_ids: prev.excluded_company_ids.filter((v) => v !== id) }));
  }

  async function save() {
    setSaving(true);
    try {
      await Promise.all([
        fetch("/api/admin/display-settings", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            setting_key: `${settingsKey}_company_category_ids`,
            setting_value: local.company_category_ids,
          }),
        }),
        fetch("/api/admin/display-settings", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            setting_key: `${settingsKey}_excluded_company_ids`,
            setting_value: local.excluded_company_ids,
          }),
        }),
      ]);
      toast.success(`${title} settings saved`);
      onSaved(settingsKey, local);
    } catch {
      toast.error(`Failed to save ${title} settings`);
    } finally {
      setSaving(false);
    }
  }

  const filteredCompanies = companies.filter((c) =>
    local.company_category_ids.length === 0
      ? true
      : true
  );

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <SlidersHorizontal className="h-5 w-5" />
          {title}
        </CardTitle>
        <CardDescription>{description}</CardDescription>
      </CardHeader>
      <CardContent className="space-y-6">
        <div>
          <h3 className="text-sm font-medium mb-3">Company Categories to Include</h3>
          {categories.length === 0 ? (
            <p className="text-sm text-muted-foreground italic">
              No categories synced yet. Run a sync to populate.
            </p>
          ) : (
            <div className="space-y-2">
              {categories.map((cat) => (
                <div key={cat.value} className="flex items-center gap-2">
                  <Checkbox
                    id={`${settingsKey}-cat-${cat.value}`}
                    checked={local.company_category_ids.includes(cat.value)}
                    onCheckedChange={() => toggleCategory(cat.value)}
                  />
                  <Label
                    htmlFor={`${settingsKey}-cat-${cat.value}`}
                    className="cursor-pointer font-normal"
                  >
                    {cat.label}
                    <span className="ml-2 text-xs text-muted-foreground">id={cat.value}</span>
                  </Label>
                </div>
              ))}
            </div>
          )}
        </div>

        <div>
          <h3 className="text-sm font-medium mb-1">Excluded Companies</h3>
          <p className="text-xs text-muted-foreground mb-2">
            Individual companies to hide even if they match the selected categories.
          </p>
          <CompanySearch
            selectedIds={local.excluded_company_ids}
            categoryIds={local.company_category_ids}
            allCompanies={filteredCompanies}
            onAdd={addExclusion}
            onRemove={removeExclusion}
          />
        </div>

        <Button onClick={save} disabled={saving} size="sm">
          {saving ? (
            <><Loader2 className="mr-2 h-4 w-4 animate-spin" />Saving…</>
          ) : (
            <><Save className="mr-2 h-4 w-4" />Save {title} Settings</>
          )}
        </Button>
      </CardContent>
    </Card>
  );
}

export default function DisplaySettingsPage() {
  const [settings, setSettings] = useState<DisplaySettings | null>(null);
  const [categories, setCategories] = useState<CompanyCategory[]>([]);
  const [companies, setCompanies] = useState<Company[]>([]);
  const [loading, setLoading] = useState(true);

  const load = useCallback(async () => {
    try {
      const [settingsRes, catsRes, companiesRes] = await Promise.all([
        fetch("/api/admin/display-settings"),
        fetch("/api/data/company-categories"),
        fetch("/api/data/companies-list"),
      ]);
      if (settingsRes.ok) setSettings(await settingsRes.json());
      if (catsRes.ok) setCategories(await catsRes.json());
      if (companiesRes.ok) setCompanies(await companiesRes.json());
    } catch {
      toast.error("Failed to load display settings");
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => { load(); }, [load]);

  function handleSaved(key: "kiosk" | "mobile", updated: SectionSettings) {
    setSettings((prev) => prev ? { ...prev, [key]: updated } : prev);
  }

  if (loading) {
    return (
      <div className="container mx-auto py-8 px-4 flex justify-center">
        <Loader2 className="h-8 w-8 animate-spin" />
      </div>
    );
  }

  if (!settings) {
    return (
      <div className="container mx-auto py-8 px-4">
        <p className="text-destructive">Failed to load settings.</p>
      </div>
    );
  }

  return (
    <>
      <PageHeader
        title="Display Settings"
        description="Configure which companies appear in the Kiosk and Mobile dashboards."
        breadcrumbs={[{ label: 'Admin', href: '/admin' }, { label: 'Display Settings' }]}
        accent
      />
      <div className="container mx-auto py-8 px-4 max-w-5xl">
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <Section
          title="Kiosk"
          description="Settings for the executive kiosk display."
          settingsKey="kiosk"
          settings={settings.kiosk}
          categories={categories}
          companies={companies}
          onSaved={handleSaved}
        />
        <Section
          title="Mobile"
          description="Settings for the mobile dashboard."
          settingsKey="mobile"
          settings={settings.mobile}
          categories={categories}
          companies={companies}
          onSaved={handleSaved}
        />
        </div>
      </div>
    </>
  );
}
