import { AlertTriangle, CheckCircle, Clock, MessageSquare, ThumbsUp, TrendingUp } from 'lucide-react';

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

import PageHeader from '@/Components/layout/PageHeader';
import { Badge } from '@/Components/ui/badge';
import { Button } from '@/Components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/Components/ui/card';
import { EmptyState } from '@/Components/ui/empty-state';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/Components/ui/table';
import AdminLayout from '@/Layouts/AdminLayout';
import { formatRelativeTime } from '@/lib/format';

interface SurveyDistribution {
  rating: string;
  count: number;
  pct: number;
}

interface SurveyTriggerStats {
  trigger: string;
  total: number;
  distribution: SurveyDistribution[];
}

interface SurveyStats {
  total_responses: number;
  by_trigger: SurveyTriggerStats[];
}

interface OpportunityFeedbackRow {
  opportunity_type: string;
  feedback_type: string;
  count: number;
}

interface TopRequested {
  opportunity_type: string;
  count: number;
}

interface OpportunityFeedbackStats {
  by_type: OpportunityFeedbackRow[];
  top_requested: TopRequested[];
}

interface Verbatim {
  user_id: number;
  trigger: string | null;
  rating: string | null;
  comment: string;
  created_at: string;
}

interface NpsStats {
  average_score: number;
  total_responses: number;
  promoters: number;
  passives: number;
  detractors: number;
  nps_score: number;
}

interface ChurnRiskDistribution {
  healthy: number;
  monitor: number;
  at_risk: number;
  critical: number;
  unscored: number;
}

interface FeedbackSlaItem {
  category: string;
  open_count: number;
  avg_age_hours: number;
}

interface OpenSubmission {
  id: number;
  category: string;
  message: string;
  url: string | null;
  user_id: number | null;
  age_hours: number;
  created_at: string;
}

interface Props {
  survey_stats: SurveyStats;
  opportunity_feedback: OpportunityFeedbackStats;
  recent_verbatims: Verbatim[];
  nps_stats: NpsStats;
  churn_risk_distribution: ChurnRiskDistribution;
  feedback_sla: FeedbackSlaItem[];
  open_submissions: OpenSubmission[];
  last_reviewed_at: string | null;
  last_report_generated_at: string | null;
}

const RATING_COLORS: Record<string, string> = {
  very_useful: 'bg-success',
  somewhat_useful: 'bg-warning',
  not_useful: 'bg-destructive',
};

const RATING_LABELS: Record<string, string> = {
  very_useful: 'Very useful',
  somewhat_useful: 'Somewhat useful',
  not_useful: 'Not useful',
};

const TRIGGER_LABELS: Record<string, string> = {
  positive_roi_viewed: 'ROI Tracking',
  milestone_recommendation_applied: 'Recommendation Applied',
  first_alert_acknowledged: 'Traffic Alerts',
  cancellation_flow: 'Cancellation Exit',
  trial_expiry: 'Trial Expiry',
  post_upgrade: 'Post Upgrade',
};

function RatingBar({ distribution }: { distribution: SurveyDistribution[] }) {
  if (distribution.length === 0) return null;

  return (
    <div className="space-y-2">
      {distribution.map((d) => (
        <div key={d.rating} className="flex items-center gap-3">
          <span className="w-32 truncate text-xs text-muted-foreground">
            {RATING_LABELS[d.rating] ?? d.rating}
          </span>
          <div className="flex-1 overflow-hidden rounded-full bg-muted h-2">
            <div
              className={`h-2 rounded-full transition-all ${RATING_COLORS[d.rating] ?? 'bg-primary'}`}
              style={{ width: `${d.pct}%` }}
            />
          </div>
          <span className="w-14 text-right text-xs text-muted-foreground">
            {d.count} ({d.pct}%)
          </span>
        </div>
      ))}
    </div>
  );
}

function NpsScoreBadge({ score }: { score: number }) {
  const color =
    score >= 50
      ? 'bg-success/10 text-success'
      : score >= 0
        ? 'bg-warning/10 text-warning'
        : 'bg-destructive/10 text-destructive';

  return (
    <span className={`inline-flex items-center rounded-md px-2.5 py-1 text-2xl font-bold ${color}`}>
      {score}
    </span>
  );
}

function NpsDistributionBar({
  promoters,
  passives,
  detractors,
  total,
}: {
  promoters: number;
  passives: number;
  detractors: number;
  total: number;
}) {
  if (total === 0) return null;

  const pPct = Math.round((promoters / total) * 100);
  const paPct = Math.round((passives / total) * 100);
  const dPct = Math.round((detractors / total) * 100);

  return (
    <div className="space-y-2">
      <div className="flex h-3 overflow-hidden rounded-full">
        {dPct > 0 && (
          <div
            className="bg-destructive"
            style={{ width: `${dPct}%` }}
            title={`Detractors: ${detractors} (${dPct}%)`}
          />
        )}
        {paPct > 0 && (
          <div
            className="bg-warning"
            style={{ width: `${paPct}%` }}
            title={`Passives: ${passives} (${paPct}%)`}
          />
        )}
        {pPct > 0 && (
          <div
            className="bg-success"
            style={{ width: `${pPct}%` }}
            title={`Promoters: ${promoters} (${pPct}%)`}
          />
        )}
      </div>
      <div className="flex justify-between text-xs text-muted-foreground">
        <span>Detractors (0-6): {detractors}</span>
        <span>Passives (7-8): {passives}</span>
        <span>Promoters (9-10): {promoters}</span>
      </div>
    </div>
  );
}

const SLA_CATEGORY_LABELS: Record<string, string> = {
  bug: 'Bugs',
  feature_request: 'Feature Requests',
  general: 'General',
};

function slaColor(avgAgeHours: number): string {
  if (avgAgeHours > 24) return 'text-destructive';
  if (avgAgeHours > 12) return 'text-warning';
  return 'text-success';
}

function slaBadgeClass(avgAgeHours: number): string {
  if (avgAgeHours > 24) return 'bg-destructive/10 text-destructive border-destructive/20';
  if (avgAgeHours > 12) return 'bg-warning/10 text-warning border-warning/20';
  return 'bg-success/10 text-success border-success/20';
}

const CATEGORY_LABELS: Record<string, string> = {
  bug: 'Bug',
  feature_request: 'Feature Request',
  general: 'General',
};

function categoryBadgeClass(category: string): string {
  if (category === 'bug') return 'bg-destructive/10 text-destructive border-destructive/20';
  if (category === 'feature_request') return 'bg-primary/10 text-primary border-primary/20';
  return 'bg-muted text-muted-foreground border-border';
}

export default function FeedbackDashboard({
  survey_stats,
  opportunity_feedback,
  recent_verbatims,
  nps_stats,
  churn_risk_distribution,
  feedback_sla,
  open_submissions,
  last_reviewed_at,
  last_report_generated_at,
}: Props) {
  const totalChurnScored =
    churn_risk_distribution.healthy +
    churn_risk_distribution.monitor +
    churn_risk_distribution.at_risk +
    churn_risk_distribution.critical;

  return (
    <AdminLayout>
      <Head title="Feedback Dashboard" />

      <div className="container py-6 space-y-6">
        <div className="flex items-start justify-between gap-4">
          <PageHeader
            title="Feedback Dashboard"
            description="NPS scores, micro-survey responses, churn risk, and opportunity feedback"
          />
          <div className="flex flex-col items-end gap-1 shrink-0">
            <Button
              variant="outline"
              size="sm"
              onClick={() =>
                router.post(route('admin.feedback-dashboard.mark-reviewed'), {}, { preserveScroll: true })
              }
            >
              <CheckCircle className="mr-1.5 h-3.5 w-3.5" />
              Mark Reviewed
            </Button>
            {last_reviewed_at && (
              <span className="text-xs text-muted-foreground">
                Last reviewed {formatRelativeTime(last_reviewed_at)}
              </span>
            )}
            {last_report_generated_at && (
              <span className="text-xs text-muted-foreground">
                Last report {formatRelativeTime(last_report_generated_at)}
              </span>
            )}
          </div>
        </div>

        {/* NPS Overview */}
        <section className="space-y-4">
          <div className="flex items-center gap-2">
            <TrendingUp className="h-5 w-5 text-muted-foreground" />
            <h2 className="text-lg font-semibold">
              NPS Score{' '}
              <span className="text-sm font-normal text-muted-foreground">(last 90 days)</span>
            </h2>
          </div>

          {nps_stats.total_responses === 0 ? (
            <EmptyState
              title="No NPS responses yet"
              description="NPS survey responses will appear here as users submit ratings."
            />
          ) : (
            <div className="grid gap-4 md:grid-cols-4">
              <Card>
                <CardHeader className="pb-2">
                  <CardDescription>NPS Score</CardDescription>
                </CardHeader>
                <CardContent>
                  <NpsScoreBadge score={nps_stats.nps_score} />
                </CardContent>
              </Card>
              <Card>
                <CardHeader className="pb-2">
                  <CardDescription>Average Rating</CardDescription>
                </CardHeader>
                <CardContent>
                  <p className="text-2xl font-bold">{nps_stats.average_score}/10</p>
                </CardContent>
              </Card>
              <Card>
                <CardHeader className="pb-2">
                  <CardDescription>Total Responses</CardDescription>
                </CardHeader>
                <CardContent>
                  <p className="text-2xl font-bold">{nps_stats.total_responses}</p>
                </CardContent>
              </Card>
              <Card className="md:col-span-1">
                <CardHeader className="pb-2">
                  <CardDescription>Distribution</CardDescription>
                </CardHeader>
                <CardContent>
                  <NpsDistributionBar
                    promoters={nps_stats.promoters}
                    passives={nps_stats.passives}
                    detractors={nps_stats.detractors}
                    total={nps_stats.total_responses}
                  />
                </CardContent>
              </Card>
            </div>
          )}
        </section>

        {/* Feedback SLA */}
        {feedback_sla.length > 0 && (
          <section className="space-y-4">
            <div className="flex items-center gap-2">
              <Clock className="h-5 w-5 text-muted-foreground" />
              <h2 className="text-lg font-semibold">Feedback SLA</h2>
              <span className="text-sm font-normal text-muted-foreground">
                — avg age of open submissions
              </span>
            </div>

            <div className="grid gap-4 md:grid-cols-3">
              {feedback_sla.map((item) => (
                <Card key={item.category}>
                  <CardHeader className="pb-2">
                    <CardDescription>
                      {SLA_CATEGORY_LABELS[item.category] ?? item.category}
                    </CardDescription>
                  </CardHeader>
                  <CardContent className="space-y-2">
                    <div className="flex items-center gap-2">
                      <span className={`text-2xl font-bold ${slaColor(item.avg_age_hours)}`}>
                        {item.avg_age_hours}h
                      </span>
                      <span
                        className={`inline-flex items-center rounded border px-1.5 py-0.5 text-xs font-medium ${slaBadgeClass(item.avg_age_hours)}`}
                      >
                        {item.avg_age_hours > 24
                          ? 'Over SLA'
                          : item.avg_age_hours > 12
                            ? 'At risk'
                            : 'On track'}
                      </span>
                    </div>
                    <p className="text-xs text-muted-foreground">{item.open_count} open</p>
                  </CardContent>
                </Card>
              ))}
            </div>
          </section>
        )}

        {/* Open Feedback Submissions */}
        <section className="space-y-4">
          <div className="flex items-center gap-2">
            <MessageSquare className="h-5 w-5 text-muted-foreground" />
            <h2 className="text-lg font-semibold">
              Open Feedback Submissions{' '}
              {open_submissions.length > 0 && (
                <Badge variant="secondary" className="ml-1 text-xs">
                  {open_submissions.length}
                </Badge>
              )}
            </h2>
          </div>

          <Card>
            <CardContent className="pt-6">
              {open_submissions.length === 0 ? (
                <EmptyState
                  title="No open submissions"
                  description="All feedback submissions have been resolved."
                />
              ) : (
                <div className="overflow-x-auto">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>Category</TableHead>
                        <TableHead>Message</TableHead>
                        <TableHead>URL</TableHead>
                        <TableHead>Age</TableHead>
                        <TableHead className="text-right">Action</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {open_submissions.map((s) => (
                        <TableRow key={s.id}>
                          <TableCell>
                            <span
                              className={`inline-flex items-center rounded border px-1.5 py-0.5 text-xs font-medium ${categoryBadgeClass(s.category)}`}
                            >
                              {CATEGORY_LABELS[s.category] ?? s.category}
                            </span>
                          </TableCell>
                          <TableCell className="max-w-xs">
                            <p className="truncate text-sm" title={s.message}>
                              {s.message}
                            </p>
                          </TableCell>
                          <TableCell className="max-w-[12rem]">
                            {s.url ? (
                              <span
                                className="truncate block text-xs text-muted-foreground"
                                title={s.url}
                              >
                                {s.url}
                              </span>
                            ) : (
                              <span className="text-xs text-muted-foreground">—</span>
                            )}
                          </TableCell>
                          <TableCell>
                            <span className={`text-xs ${slaColor(s.age_hours)}`}>
                              {s.age_hours}h
                            </span>
                          </TableCell>
                          <TableCell className="text-right">
                            <Button
                              size="sm"
                              variant="outline"
                              onClick={() =>
                                router.post(
                                  route('admin.feedback-submissions.resolve', { submission: s.id }),
                                  {},
                                  { preserveScroll: true },
                                )
                              }
                            >
                              <CheckCircle className="mr-1.5 h-3.5 w-3.5" />
                              Resolve
                            </Button>
                          </TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </div>
              )}
            </CardContent>
          </Card>
        </section>

        {/* Churn Risk Distribution */}
        <section className="space-y-4">
          <div className="flex items-center gap-2">
            <AlertTriangle className="h-5 w-5 text-muted-foreground" />
            <h2 className="text-lg font-semibold">Churn Risk Distribution</h2>
          </div>

          <div className="grid gap-4 md:grid-cols-5">
            <Card>
              <CardHeader className="pb-2">
                <CardDescription>
                  <span className="flex items-center gap-1.5">
                    <span className="h-2 w-2 rounded-full bg-success" aria-hidden="true" />
                    Healthy
                  </span>
                </CardDescription>
              </CardHeader>
              <CardContent>
                <p className="text-2xl font-bold text-success">
                  <span className="sr-only">Healthy count: </span>
                  {churn_risk_distribution.healthy}
                </p>
                {totalChurnScored > 0 && (
                  <p className="text-xs text-muted-foreground">
                    {Math.round((churn_risk_distribution.healthy / totalChurnScored) * 100)}%
                  </p>
                )}
              </CardContent>
            </Card>
            <Card>
              <CardHeader className="pb-2">
                <CardDescription>
                  <span className="flex items-center gap-1.5">
                    <span className="h-2 w-2 rounded-full bg-warning" aria-hidden="true" />
                    Monitor
                  </span>
                </CardDescription>
              </CardHeader>
              <CardContent>
                <p className="text-2xl font-bold text-warning">
                  <span className="sr-only">Monitor count: </span>
                  {churn_risk_distribution.monitor}
                </p>
                {totalChurnScored > 0 && (
                  <p className="text-xs text-muted-foreground">
                    {Math.round((churn_risk_distribution.monitor / totalChurnScored) * 100)}%
                  </p>
                )}
              </CardContent>
            </Card>
            <Card>
              <CardHeader className="pb-2">
                <CardDescription>
                  <span className="flex items-center gap-1.5">
                    <span className="h-2 w-2 rounded-full bg-warning-high" aria-hidden="true" />
                    At Risk
                  </span>
                </CardDescription>
              </CardHeader>
              <CardContent>
                <p className="text-2xl font-bold text-warning-high">
                  <span className="sr-only">At Risk count: </span>
                  {churn_risk_distribution.at_risk}
                </p>
                {totalChurnScored > 0 && (
                  <p className="text-xs text-muted-foreground">
                    {Math.round((churn_risk_distribution.at_risk / totalChurnScored) * 100)}%
                  </p>
                )}
              </CardContent>
            </Card>
            <Card>
              <CardHeader className="pb-2">
                <CardDescription>
                  <span className="flex items-center gap-1.5">
                    <span className="h-2 w-2 rounded-full bg-destructive" aria-hidden="true" />
                    Critical
                  </span>
                </CardDescription>
              </CardHeader>
              <CardContent>
                <p className="text-2xl font-bold text-destructive">
                  <span className="sr-only">Critical count: </span>
                  {churn_risk_distribution.critical}
                </p>
                {totalChurnScored > 0 && (
                  <p className="text-xs text-muted-foreground">
                    {Math.round((churn_risk_distribution.critical / totalChurnScored) * 100)}%
                  </p>
                )}
              </CardContent>
            </Card>
            <Card>
              <CardHeader className="pb-2">
                <CardDescription>
                  <span className="flex items-center gap-1.5">
                    <span
                      className="h-2 w-2 rounded-full bg-muted-foreground/40"
                      aria-hidden="true"
                    />
                    Unscored
                  </span>
                </CardDescription>
              </CardHeader>
              <CardContent>
                <p className="text-2xl font-bold text-muted-foreground">
                  <span className="sr-only">Unscored count: </span>
                  {churn_risk_distribution.unscored}
                </p>
              </CardContent>
            </Card>
          </div>
        </section>

        {/* Survey Responses */}
        <section className="space-y-4">
          <div className="flex items-center gap-2">
            <MessageSquare className="h-5 w-5 text-muted-foreground" />
            <h2 className="text-lg font-semibold">
              Survey Responses{' '}
              <span className="text-sm font-normal text-muted-foreground">
                ({survey_stats.total_responses} total)
              </span>
            </h2>
          </div>

          {survey_stats.by_trigger.length === 0 ? (
            <EmptyState
              title="No survey responses yet"
              description="Micro-survey responses will appear here once users interact with the feature."
            />
          ) : (
            <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
              {survey_stats.by_trigger.map((stat) => (
                <Card key={stat.trigger}>
                  <CardHeader className="pb-3">
                    <CardTitle className="text-base">
                      {TRIGGER_LABELS[stat.trigger] ?? stat.trigger}
                    </CardTitle>
                    <CardDescription>
                      {stat.total} response{stat.total !== 1 ? 's' : ''}
                    </CardDescription>
                  </CardHeader>
                  <CardContent>
                    <RatingBar distribution={stat.distribution} />
                  </CardContent>
                </Card>
              ))}
            </div>
          )}
        </section>

        {/* Top Requested Features */}
        <section className="space-y-4">
          <div className="flex items-center gap-2">
            <ThumbsUp className="h-5 w-5 text-muted-foreground" />
            <h2 className="text-lg font-semibold">Top Requested Opportunity Types</h2>
          </div>

          <Card>
            <CardContent className="pt-6">
              {opportunity_feedback.top_requested.length === 0 ? (
                <EmptyState
                  title="No opportunity feedback yet"
                  description="Users who upvote opportunities on the Opportunity Map will appear here."
                />
              ) : (
                <div className="overflow-x-auto">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>Opportunity Type</TableHead>
                        <TableHead className="text-right">Upvotes</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {opportunity_feedback.top_requested.map((row) => (
                        <TableRow key={row.opportunity_type}>
                          <TableCell className="font-medium">
                            {row.opportunity_type.replace(/_/g, ' ')}
                          </TableCell>
                          <TableCell className="text-right">
                            <Badge variant="secondary">{row.count}</Badge>
                          </TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </div>
              )}
            </CardContent>
          </Card>
        </section>

        {/* Recent Verbatims */}
        <section className="space-y-4">
          <h2 className="text-lg font-semibold">Recent Comments</h2>

          <Card>
            <CardContent className="pt-6">
              {recent_verbatims.length === 0 ? (
                <EmptyState
                  title="No comments yet"
                  description="User comments from survey responses will appear here."
                />
              ) : (
                <div className="space-y-4">
                  {recent_verbatims.map((v, i) => (
                    <div key={i} className="border-b pb-4 last:border-0 last:pb-0">
                      <div className="mb-1 flex items-center gap-2 text-xs text-muted-foreground">
                        <Badge variant="outline" className="text-xs">
                          {TRIGGER_LABELS[v.trigger ?? ''] ?? v.trigger ?? 'Unknown'}
                        </Badge>
                        {v.rating && (
                          <Badge
                            variant="outline"
                            className={`text-xs ${
                              v.rating === 'very_useful'
                                ? 'border-success text-success'
                                : v.rating === 'not_useful'
                                  ? 'border-destructive text-destructive'
                                  : 'border-warning text-warning'
                            }`}
                          >
                            {RATING_LABELS[v.rating] ?? v.rating}
                          </Badge>
                        )}
                        <span className="ml-auto">{formatRelativeTime(v.created_at)}</span>
                      </div>
                      <p className="text-sm text-foreground">{v.comment}</p>
                    </div>
                  ))}
                </div>
              )}
            </CardContent>
          </Card>
        </section>
      </div>
    </AdminLayout>
  );
}
