import Link from 'next/link';
import { Bot, Receipt, FileText, Brain, ExternalLink } from 'lucide-react';

import {
  SettingsFormCard,
  type SettingFieldDef,
} from '@/components/admin/shared/settings-form-card';
import { PageHeader } from '@/components/shared/page-header';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';

const MASTER_FIELDS: SettingFieldDef[] = [
  {
    key: 'ai_enabled',
    label: 'AI features enabled',
    description:
      'Master switch. When OFF, every AI surface (receipt OCR fallback, berth-PDF AI parse, future embedding-driven recommendations) is bypassed. Provider keys stay configured but unused.',
    type: 'boolean',
    defaultValue: true,
  },
  {
    key: 'ai_monthly_token_cap',
    label: 'Monthly token cap (this port)',
    description:
      'Soft cap on total AI tokens consumed per calendar month across every feature. When exceeded, AI features fall back to non-AI paths and surface a banner. Set 0 for no cap.',
    type: 'number',
    defaultValue: 0,
  },
];

const PROVIDER_FIELDS: SettingFieldDef[] = [
  {
    key: 'openai_api_key',
    label: 'OpenAI API key',
    description:
      'Used by Receipt OCR fallback and (future) berth-PDF AI parse. Stored AES-encrypted at rest; the field shows blank after save.',
    type: 'password',
    placeholder: 'sk-…',
    defaultValue: '',
  },
  {
    key: 'openai_default_model',
    label: 'Default OpenAI model',
    description: 'Used when a feature does not specify an explicit model.',
    type: 'select',
    defaultValue: 'gpt-4o-mini',
    options: [
      { value: 'gpt-4o-mini', label: 'gpt-4o-mini — cheap, fast, vision-capable' },
      { value: 'gpt-4o', label: 'gpt-4o — full-strength multimodal' },
      { value: 'gpt-4-turbo', label: 'gpt-4-turbo — legacy text reasoning' },
    ],
  },
];

interface FeatureLink {
  href: string;
  icon: typeof Bot;
  title: string;
  description: string;
}

const FEATURE_LINKS: FeatureLink[] = [
  {
    href: '../ocr',
    icon: Receipt,
    title: 'Receipt OCR settings',
    description:
      'Provider, model, and confidence thresholds for the receipt scanner. AI fallback only runs when the on-device parser is uncertain.',
  },
  {
    href: '../berth-pdf-parser',
    icon: FileText,
    title: 'Berth PDF parser',
    description:
      'Three-tier AcroForm → OCR → AI pipeline. The AI pass costs tokens; reps invoke it manually when OCR confidence is low.',
  },
  {
    href: '../recommender',
    icon: Brain,
    title: 'Berth recommender',
    description:
      'Rule-based today; future versions will optionally use embeddings for soft preference matching. AI use is gated by the master switch above.',
  },
];

export default function AiAdminPage() {
  return (
    <div className="space-y-6">
      <PageHeader
        title="AI configuration"
        description="One place to manage every AI-using feature. Provider credentials and the master AI switch live here; per-feature thresholds remain in their dedicated pages, linked below."
        eyebrow="ADMIN"
      />

      <SettingsFormCard
        title="Master controls"
        description="Hard kill switch + budget guardrails covering every AI surface in this port."
        fields={MASTER_FIELDS}
      />

      <SettingsFormCard
        title="Provider credentials"
        description="Shared API keys used by AI-enabled features. Per-feature pages can override the model on a feature-by-feature basis."
        fields={PROVIDER_FIELDS}
      />

      <Card>
        <CardHeader>
          <CardTitle className="text-base flex items-center gap-2">
            <Bot className="h-4 w-4" /> Per-feature settings
          </CardTitle>
          <CardDescription>
            Feature-specific tuning lives on each feature&apos;s admin page. They all read the
            master switch + provider credentials configured above.
          </CardDescription>
        </CardHeader>
        <CardContent className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
          {FEATURE_LINKS.map((f) => (
            <Link
              key={f.href}
              href={f.href as never}
              className="rounded-md border bg-card p-3 hover:border-primary transition-colors block"
            >
              <div className="flex items-center gap-2 text-sm font-medium">
                <f.icon className="h-4 w-4 text-muted-foreground" />
                {f.title}
                <ExternalLink className="ml-auto h-3 w-3 opacity-50" />
              </div>
              <p className="mt-1 text-xs text-muted-foreground">{f.description}</p>
            </Link>
          ))}
        </CardContent>
      </Card>
    </div>
  );
}
