import { Search } from 'lucide-react';

import { useRef } from 'react';

import { Head, Link } from '@inertiajs/react';

import { AdminDataTable } from '@/Components/admin/AdminDataTable';
import { ChartErrorBoundary } from '@/Components/admin/ChartErrorBoundary';
import { PerPageSelector } from '@/Components/admin/PerPageSelector';
import { SortHeader } from '@/Components/admin/SortHeader';
import PageHeader from '@/Components/layout/PageHeader';
import { Badge } from '@/Components/ui/badge';
import {
  Breadcrumb,
  BreadcrumbItem,
  BreadcrumbLink,
  BreadcrumbList,
  BreadcrumbPage,
  BreadcrumbSeparator,
} from '@/Components/ui/breadcrumb';
import { ExportButton } from '@/Components/ui/export-button';
import { Input } from '@/Components/ui/input';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/Components/ui/select';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/Components/ui/table';
import { useAdminFilters } from '@/hooks/useAdminFilters';
import { useAdminKeyboardShortcuts } from '@/hooks/useAdminKeyboardShortcuts';
import { useNavigationState } from '@/hooks/useNavigationState';
import AdminLayout from '@/Layouts/AdminLayout';
import { formatRelativeTime } from '@/lib/format';
import type { PaginatedResponse } from '@/types';

interface NpsSurveyRow {
  id: number;
  user_id: number;
  user_name: string | null;
  user_email: string | null;
  score: number;
  reason: string | null;
  survey_type: string;
  created_at: string;
}

interface NpsStats {
  total_responses: number;
  promoters: number;
  passives: number;
  detractors: number;
  nps_score: number;
  average_score: number;
  histogram: Record<string, number>;
}

interface Props {
  surveys: PaginatedResponse<NpsSurveyRow>;
  filters: {
    search?: string;
    score?: string;
    survey_type?: string;
    date_from?: string;
    date_to?: string;
    sort?: string;
    dir?: string;
    per_page?: number;
  };
  stats: NpsStats;
  survey_types: string[];
}

function scoreLabel(score: number): string {
  if (score >= 9) return 'Promoter';
  if (score >= 7) return 'Passive';
  return 'Detractor';
}

function scoreBadgeVariant(score: number): 'default' | 'secondary' | 'destructive' {
  if (score >= 9) return 'default';
  if (score >= 7) return 'secondary';
  return 'destructive';
}

function NpsHistogram({ histogram, total }: { histogram: Record<string, number>; total: number }) {
  const maxCount = Math.max(...Object.values(histogram), 1);
  return (
    <div className="flex items-end gap-1 h-16" aria-label="NPS score distribution">
      {Array.from({ length: 11 }, (_, i) => {
        const count = histogram[String(i)] ?? 0;
        const heightPct = Math.round((count / maxCount) * 100);
        const color = i >= 9 ? 'bg-green-500' : i >= 7 ? 'bg-yellow-400' : 'bg-red-400';
        return (
          <div key={i} className="flex flex-col items-center gap-0.5 flex-1">
            <div
              className={`w-full rounded-sm ${color}`}
              style={{ height: `${heightPct}%`, minHeight: count > 0 ? 2 : 0 }}
              title={`Score ${i}: ${count} (${total > 0 ? Math.round((count / total) * 100) : 0}%)`}
            />
            <span className="text-[10px] text-muted-foreground leading-none">{i}</span>
          </div>
        );
      })}
    </div>
  );
}

export default function AdminNpsSurveysIndex({ surveys, filters, stats, survey_types }: Props) {
  const searchInputRef = useRef<HTMLInputElement>(null);
  const { search, setSearch, updateFilter, handleSort, handlePage } = useAdminFilters({
    route: '/admin/nps-surveys',
    filters,
  });
  const isNavigating = useNavigationState();

  const exportParams: Record<string, string> = {};
  if (filters.search) exportParams.search = filters.search;
  if (filters.score) exportParams.score = filters.score;
  if (filters.survey_type) exportParams.survey_type = filters.survey_type;
  if (filters.date_from) exportParams.date_from = filters.date_from;
  if (filters.date_to) exportParams.date_to = filters.date_to;

  useAdminKeyboardShortcuts({
    onSearch: () => searchInputRef.current?.focus(),
    onNextPage: surveys.current_page < surveys.last_page ? () => handlePage(surveys.current_page + 1) : undefined,
    onPrevPage: surveys.current_page > 1 ? () => handlePage(surveys.current_page - 1) : undefined,
  });

  return (
    <AdminLayout>
      <Head title="Admin - NPS Surveys" />
      <div className="container pt-6">
        <Breadcrumb>
          <BreadcrumbList>
            <BreadcrumbItem>
              <BreadcrumbLink asChild>
                <Link href="/admin">Admin</Link>
              </BreadcrumbLink>
            </BreadcrumbItem>
            <BreadcrumbSeparator />
            <BreadcrumbItem>
              <BreadcrumbPage>NPS Surveys</BreadcrumbPage>
            </BreadcrumbItem>
          </BreadcrumbList>
        </Breadcrumb>
      </div>

      <PageHeader
        title="NPS Surveys"
        subtitle="Customer satisfaction scores and verbatim feedback (last 90 days)"
        actions={<ExportButton href={route('admin.nps-surveys.export')} params={exportParams} />}
      />

      <div className="container py-8 space-y-6">
        {/* Stats banner */}
        <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-4">
          <div className="rounded-lg border bg-card p-4 space-y-1">
            <div className="text-xs text-muted-foreground">NPS Score</div>
            <div className={`text-2xl font-bold ${stats.nps_score >= 50 ? 'text-green-600 dark:text-green-400' : stats.nps_score >= 0 ? 'text-yellow-600 dark:text-yellow-400' : 'text-red-600 dark:text-red-400'}`}>
              {stats.nps_score > 0 ? '+' : ''}{stats.nps_score}
            </div>
          </div>
          <div className="rounded-lg border bg-card p-4 space-y-1">
            <div className="text-xs text-muted-foreground">Avg Score</div>
            <div className="text-2xl font-bold">{stats.average_score}</div>
          </div>
          <div className="rounded-lg border bg-card p-4 space-y-1">
            <div className="text-xs text-muted-foreground">Responses</div>
            <div className="text-2xl font-bold">{stats.total_responses}</div>
          </div>
          <div className="rounded-lg border bg-card p-4 space-y-1">
            <div className="text-xs text-muted-foreground">Promoters (9–10)</div>
            <div className="text-2xl font-bold text-green-600 dark:text-green-400">{stats.promoters}</div>
          </div>
          <div className="rounded-lg border bg-card p-4 space-y-1">
            <div className="text-xs text-muted-foreground">Passives (7–8)</div>
            <div className="text-2xl font-bold text-yellow-600 dark:text-yellow-400">{stats.passives}</div>
          </div>
          <div className="rounded-lg border bg-card p-4 space-y-1">
            <div className="text-xs text-muted-foreground">Detractors (0–6)</div>
            <div className="text-2xl font-bold text-red-600 dark:text-red-400">{stats.detractors}</div>
          </div>
        </div>

        {/* Score histogram */}
        <div className="rounded-lg border bg-card p-4 space-y-2">
          <div className="text-sm font-medium text-muted-foreground">Score Distribution</div>
          <NpsHistogram histogram={stats.histogram} total={stats.total_responses} />
        </div>

        {/* Filters */}
        <fieldset className="flex flex-col sm:flex-row gap-3 sm:items-center flex-wrap">
          <legend className="sr-only">NPS Survey Filters</legend>
          <Input
            ref={searchInputRef}
            placeholder="Search by user name or email..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="max-w-sm"
            aria-label="Search NPS surveys"
          />
          <Select
            value={filters.score ?? 'all'}
            onValueChange={(v) => updateFilter({ score: v === 'all' ? undefined : v })}
          >
            <SelectTrigger className="w-[160px]" aria-label="Filter by score">
              <SelectValue placeholder="All Scores" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">All Scores</SelectItem>
              {Array.from({ length: 11 }, (_, i) => (
                <SelectItem key={i} value={String(i)}>{i} — {scoreLabel(i)}</SelectItem>
              ))}
            </SelectContent>
          </Select>
          {survey_types.length > 0 && (
            <Select
              value={filters.survey_type ?? 'all'}
              onValueChange={(v) => updateFilter({ survey_type: v === 'all' ? undefined : v })}
            >
              <SelectTrigger className="w-[180px]" aria-label="Filter by survey type">
                <SelectValue placeholder="All Types" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Types</SelectItem>
                {survey_types.map((t) => (
                  <SelectItem key={t} value={t}>{t}</SelectItem>
                ))}
              </SelectContent>
            </Select>
          )}
          <div className="sm:ml-auto">
            <PerPageSelector
              value={filters.per_page ?? 50}
              onChange={(perPage) => updateFilter({ per_page: perPage })}
            />
          </div>
        </fieldset>

        <ChartErrorBoundary label="Unable to load NPS surveys table">
          <AdminDataTable
            isEmpty={surveys.data.length === 0}
            isNavigating={isNavigating}
            isLoading={isNavigating}
            pagination={surveys}
            onPage={handlePage}
            paginationLabel="surveys"
            emptyIcon={Search}
            emptyTitle="No NPS surveys found"
            emptyDescription="NPS survey responses will appear here once users submit scores."
          >
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>ID</TableHead>
                  <TableHead>User</TableHead>
                  <SortHeader column="score" label="Score" currentSort={filters.sort} currentDir={filters.dir} onSort={handleSort} />
                  <TableHead>Type</TableHead>
                  <TableHead>Reason</TableHead>
                  <SortHeader column="created_at" label="Submitted" currentSort={filters.sort} currentDir={filters.dir} onSort={handleSort} />
                </TableRow>
              </TableHeader>
              <TableBody>
                {surveys.data.map((survey) => (
                  <TableRow key={survey.id}>
                    <TableCell className="font-mono text-xs text-muted-foreground">#{survey.id}</TableCell>
                    <TableCell>
                      {survey.user_name ? (
                        <>
                          <div className="font-medium text-sm">{survey.user_name}</div>
                          {survey.user_email && (
                            <Link
                              href={`/admin/users?search=${encodeURIComponent(survey.user_email)}`}
                              className="text-xs text-muted-foreground hover:underline"
                            >
                              {survey.user_email}
                            </Link>
                          )}
                        </>
                      ) : (
                        <span className="text-xs text-muted-foreground">User #{survey.user_id}</span>
                      )}
                    </TableCell>
                    <TableCell>
                      <Badge variant={scoreBadgeVariant(survey.score)}>
                        {survey.score} — {scoreLabel(survey.score)}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      <Badge variant="outline">{survey.survey_type}</Badge>
                    </TableCell>
                    <TableCell className="max-w-xs">
                      {survey.reason ? (
                        <span className="text-sm text-muted-foreground line-clamp-2">{survey.reason}</span>
                      ) : (
                        <span className="text-xs text-muted-foreground">—</span>
                      )}
                    </TableCell>
                    <TableCell className="text-sm text-muted-foreground whitespace-nowrap">
                      {survey.created_at ? formatRelativeTime(survey.created_at) : '—'}
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </AdminDataTable>
        </ChartErrorBoundary>
      </div>
    </AdminLayout>
  );
}
