import { useCallback, useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import {
  ArrowLeft,
  BadgeCheck,
  Database,
  EyeOff,
  FileText,
  Fingerprint,
  LockKeyhole,
  RadioTower,
  ShieldCheck,
  UserRoundCog,
  type LucideIcon,
} from 'lucide-react';
import { api } from '@/api';
import { useAuth } from '@/hooks/useAuth';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';

const iconByTitle: Record<string, LucideIcon> = {
  Overview: ShieldCheck,
  'Data Collection': Database,
  'Version Checking': RadioTower,
  'Administrative Access': UserRoundCog,
  Logging: FileText,
  'Third-Party Services': EyeOff,
  Security: LockKeyhole,
  'Changes to This Policy': BadgeCheck,
  Contact: Fingerprint,
};

interface PrivacySection {
  title: string;
  items: string[];
}

interface PrivacyDoc {
  name?: string;
  summary?: string;
  last_updated?: string;
  sections?: PrivacySection[];
}

export default function PrivacyPage() {
  const { user } = useAuth();
  const [privacy, setPrivacy] = useState<PrivacyDoc | null>(null);
  const [loading, setLoading] = useState(true);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      setPrivacy((await api.privacy()) as PrivacyDoc);
    } finally {
      setLoading(false);
    }
  }, []);

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

  const sections = privacy?.sections || [];
  const updated = privacy?.last_updated
    ? new Date(privacy.last_updated).toLocaleDateString(undefined, {
        month: 'long',
        day: 'numeric',
        year: 'numeric',
      })
    : null;

  return (
    <div className="min-h-screen bg-[radial-gradient(circle_at_top_left,oklch(var(--primary)/0.06),transparent_34rem),linear-gradient(180deg,oklch(var(--background)),oklch(var(--muted)/0.18))] px-4 py-8 text-foreground sm:px-6">
      <main className="mx-auto w-full max-w-3xl space-y-5">
        <Button asChild variant="ghost" size="sm" className="-ml-2">
          <Link to={user ? '/about' : '/about'}>
            <ArrowLeft className="h-3.5 w-3.5" />
            Back to About
          </Link>
        </Button>

        <Card className="border-border/70 bg-card shadow-sm">
          <CardHeader className="pb-4">
            <div className="flex items-start justify-between gap-4">
              <div className="flex h-11 w-11 items-center justify-center rounded-xl border border-border/70 bg-primary/10 text-primary">
                <ShieldCheck className="h-5 w-5" />
              </div>
              {updated && (
                <div className="rounded-full border border-border/70 bg-background/70 px-3 py-1 text-xs text-muted-foreground">
                  Updated {updated}
                </div>
              )}
            </div>
            <CardTitle className="text-3xl tracking-tight">{privacy?.name || 'Privacy'}</CardTitle>
            <CardDescription className="max-w-2xl text-base leading-7">
              {loading ? 'Loading privacy details...' : privacy?.summary}
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-5">
            <div className="grid gap-3 sm:grid-cols-3">
              {[
                ['Local-first', 'Data stays in your installation'],
                ['No telemetry', 'No analytics or ad tracking'],
                ['User-owned', 'Login details stay in user view'],
              ].map(([label, text]) => (
                <div
                  key={label}
                  className="rounded-xl border border-border/70 bg-background/65 p-4"
                >
                  <p className="text-xs font-semibold uppercase tracking-wide text-primary">
                    {label}
                  </p>
                  <p className="mt-1 text-sm text-muted-foreground">{text}</p>
                </div>
              ))}
            </div>

            {sections.map((section, index) => {
              const Icon = iconByTitle[section.title] || ShieldCheck;
              return (
                <section
                  key={section.title}
                  className="rounded-xl border border-border/70 bg-background/65 p-5"
                >
                  <div className="flex items-start gap-3">
                    <div className="mt-0.5 flex h-9 w-9 shrink-0 items-center justify-center rounded-lg border border-border/70 bg-muted/35 text-primary">
                      <Icon className="h-4 w-4" />
                    </div>
                    <div className="min-w-0">
                      <div className="flex items-center gap-2">
                        <span className="font-mono text-xs text-muted-foreground/70">
                          {String(index + 1).padStart(2, '0')}
                        </span>
                        <h2 className="text-base font-semibold">{section.title}</h2>
                      </div>
                      <ul className="mt-3 space-y-2.5 text-sm leading-6 text-muted-foreground">
                        {section.items.map((item) => (
                          <li key={item} className="flex gap-2">
                            <span className="mt-2 h-1.5 w-1.5 shrink-0 rounded-full bg-primary/70" />
                            <span>{item}</span>
                          </li>
                        ))}
                      </ul>
                    </div>
                  </div>
                </section>
              );
            })}

            <div className="rounded-xl border border-emerald-500/20 bg-emerald-500/10 p-4 text-sm leading-6 text-emerald-700 dark:text-emerald-300">
              Login history shown in your Profile modal is for your account view. It is not shown on
              the Admin page.
            </div>
          </CardContent>
        </Card>
      </main>
    </div>
  );
}
