"use client";

import * as React from "react";
import { useApi } from "@/lib/hooks/use-api";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { LoadingState, ErrorState, EmptyState } from "@/components/ui/api-states";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  TrendingUp,
  TrendingDown,
  DollarSign,
  Target,
  ArrowUpRight,
  ArrowDownRight,
  BarChart3,
} from "lucide-react";
import { cn } from "@/lib/utils";
import type { ROIReport, ABComparisonResponse, BrandAttributionSummary } from "@/lib/api/attribution";

export default function ROIPage() {
  const [selectedBrandId, setSelectedBrandId] = React.useState<string | null>(null);

  const {
    data: roiData,
    isLoading: roiLoading,
    error: roiError,
    refresh: roiRefresh,
  } = useApi<ROIReport>(
    selectedBrandId ? `/api/v1/attribution/roi/${selectedBrandId}` : null
  );

  const {
    data: abData,
    isLoading: abLoading,
  } = useApi<ABComparisonResponse>(
    selectedBrandId ? `/api/v1/attribution/ab-comparison/${selectedBrandId}` : null
  );

  const {
    data: summaryData,
    isLoading: summaryLoading,
  } = useApi<BrandAttributionSummary>(
    selectedBrandId ? `/api/v1/attribution/brand/${selectedBrandId}` : null
  );

  if (!selectedBrandId) {
    return (
      <div className="space-y-6">
        <div>
          <h1 className="text-2xl font-bold tracking-tight">效果归因与ROI报告</h1>
          <p className="text-muted-foreground">
            追踪内容发布效果，计算投资回报率
          </p>
        </div>
        <EmptyState
          icon={<BarChart3 className="h-6 w-6 text-muted-foreground" />}
          message="请选择品牌"
          description="在品牌管理页面选择一个品牌后查看ROI报告"
        />
      </div>
    );
  }

  if (roiLoading || abLoading || summaryLoading) {
    return (
      <div className="space-y-6">
        <div>
          <h1 className="text-2xl font-bold tracking-tight">效果归因与ROI报告</h1>
          <p className="text-muted-foreground">
            追踪内容发布效果，计算投资回报率
          </p>
        </div>
        <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
          {Array.from({ length: 4 }).map((_, i) => (
            <Card key={i}>
              <CardContent className="p-6">
                <div className="space-y-2">
                  <div className="h-4 w-20 rounded bg-muted animate-pulse" />
                  <div className="h-8 w-16 rounded bg-muted animate-pulse" />
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      </div>
    );
  }

  if (roiError) {
    return (
      <div className="space-y-6">
        <div>
          <h1 className="text-2xl font-bold tracking-tight">效果归因与ROI报告</h1>
          <p className="text-muted-foreground">
            追踪内容发布效果，计算投资回报率
          </p>
        </div>
        <ErrorState error={roiError} onRetry={roiRefresh} />
      </div>
    );
  }

  const roi = roiData;
  const ab = abData;

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold tracking-tight">效果归因与ROI报告</h1>
        <p className="text-muted-foreground">
          追踪内容发布效果，计算投资回报率
        </p>
      </div>

      {roi && (
        <>
          <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
            <Card>
              <CardContent className="p-6">
                <div className="flex items-center justify-between">
                  <div className="space-y-1">
                    <p className="text-sm font-medium text-muted-foreground">ROI</p>
                    <p className={cn(
                      "text-2xl font-bold tracking-tight",
                      roi.roi_percentage >= 0 ? "text-emerald-600" : "text-red-600"
                    )}>
                      {roi.roi_percentage >= 0 ? "+" : ""}{roi.roi_percentage}%
                    </p>
                  </div>
                  <div className={cn(
                    "flex h-12 w-12 items-center justify-center rounded-lg",
                    roi.roi_percentage >= 0 ? "bg-emerald-50" : "bg-red-50"
                  )}>
                    {roi.roi_percentage >= 0
                      ? <TrendingUp className="h-6 w-6 text-emerald-600" />
                      : <TrendingDown className="h-6 w-6 text-red-600" />
                    }
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardContent className="p-6">
                <div className="flex items-center justify-between">
                  <div className="space-y-1">
                    <p className="text-sm font-medium text-muted-foreground">价值产出</p>
                    <p className="text-2xl font-bold tracking-tight">
                      ¥{roi.value_generated.toLocaleString()}
                    </p>
                  </div>
                  <div className="flex h-12 w-12 items-center justify-center rounded-lg bg-blue-50">
                    <DollarSign className="h-6 w-6 text-blue-600" />
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardContent className="p-6">
                <div className="flex items-center justify-between">
                  <div className="space-y-1">
                    <p className="text-sm font-medium text-muted-foreground">订阅成本</p>
                    <p className="text-2xl font-bold tracking-tight">
                      ¥{roi.subscription_cost.toLocaleString()}
                    </p>
                    <p className="text-xs text-muted-foreground">
                      当前套餐: {roi.current_plan}
                    </p>
                  </div>
                  <div className="flex h-12 w-12 items-center justify-center rounded-lg bg-amber-50">
                    <Target className="h-6 w-6 text-amber-600" />
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardContent className="p-6">
                <div className="flex items-center justify-between">
                  <div className="space-y-1">
                    <p className="text-sm font-medium text-muted-foreground">分数提升</p>
                    <p className={cn(
                      "text-2xl font-bold tracking-tight",
                      roi.total_score_delta >= 0 ? "text-emerald-600" : "text-red-600"
                    )}>
                      {roi.total_score_delta >= 0 ? "+" : ""}{roi.total_score_delta}
                    </p>
                    <p className="text-xs text-muted-foreground">
                      盈亏平衡: {roi.break_even_delta}
                    </p>
                  </div>
                  <div className="flex h-12 w-12 items-center justify-center rounded-lg bg-purple-50">
                    <BarChart3 className="h-6 w-6 text-purple-600" />
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>

          {ab && ab.dimensions.length > 0 && (
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <BarChart3 className="h-5 w-5" />
                  A/B 对比分析
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="mb-4 flex items-center gap-4">
                  <div className="text-sm text-muted-foreground">
                    整体变化:
                    <span className={cn(
                      "ml-2 font-bold",
                      ab.overall_delta >= 0 ? "text-emerald-600" : "text-red-600"
                    )}>
                      {ab.overall_delta >= 0 ? "+" : ""}{ab.overall_delta}
                    </span>
                    <span className="ml-1 text-muted-foreground">
                      ({ab.overall_before} → {ab.overall_after})
                    </span>
                  </div>
                </div>
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>维度</TableHead>
                      <TableHead className="text-right">发布前</TableHead>
                      <TableHead className="text-right">发布后</TableHead>
                      <TableHead className="text-right">变化</TableHead>
                      <TableHead className="text-center">状态</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {ab.dimensions.map((dim) => (
                      <TableRow key={dim.name}>
                        <TableCell className="font-medium">{dim.name}</TableCell>
                        <TableCell className="text-right">{dim.before}</TableCell>
                        <TableCell className="text-right">{dim.after}</TableCell>
                        <TableCell className={cn(
                          "text-right font-medium",
                          dim.delta > 0 ? "text-emerald-600" : dim.delta < 0 ? "text-red-600" : ""
                        )}>
                          {dim.delta > 0 ? "+" : ""}{dim.delta}
                        </TableCell>
                        <TableCell className="text-center">
                          {dim.improved ? (
                            <Badge variant="default" className="bg-emerald-100 text-emerald-700 hover:bg-emerald-100">
                              <ArrowUpRight className="mr-1 h-3 w-3" />
                              提升
                            </Badge>
                          ) : (
                            <Badge variant="secondary" className="bg-red-100 text-red-700 hover:bg-red-100">
                              <ArrowDownRight className="mr-1 h-3 w-3" />
                              下降
                            </Badge>
                          )}
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </CardContent>
            </Card>
          )}

          <Card>
            <CardHeader>
              <CardTitle>归因追踪记录</CardTitle>
            </CardHeader>
            <CardContent>
              {roi.tracking_records.length === 0 ? (
                <EmptyState
                  icon={<BarChart3 className="h-6 w-6 text-muted-foreground" />}
                  message="暂无追踪记录"
                  description="发布内容后将自动开始归因追踪"
                />
              ) : (
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>状态</TableHead>
                      <TableHead>基准分数</TableHead>
                      <TableHead>当前分数</TableHead>
                      <TableHead>分数变化</TableHead>
                      <TableHead>ROI</TableHead>
                      <TableHead>创建时间</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {roi.tracking_records.map((record) => (
                      <TableRow key={record.id}>
                        <TableCell>
                          <Badge
                            variant={
                              record.status === "tracking" ? "default" :
                              record.status === "completed" ? "secondary" : "outline"
                            }
                          >
                            {record.status === "tracking" ? "追踪中" :
                             record.status === "completed" ? "已完成" : "已过期"}
                          </Badge>
                        </TableCell>
                        <TableCell>{record.baseline_score}</TableCell>
                        <TableCell>{record.current_score ?? "-"}</TableCell>
                        <TableCell className={cn(
                          "font-medium",
                          (record.score_delta ?? 0) > 0 ? "text-emerald-600" :
                          (record.score_delta ?? 0) < 0 ? "text-red-600" : ""
                        )}>
                          {record.score_delta != null
                            ? `${record.score_delta > 0 ? "+" : ""}${record.score_delta}`
                            : "-"}
                        </TableCell>
                        <TableCell>
                          {record.roi_percentage != null
                            ? `${record.roi_percentage > 0 ? "+" : ""}${record.roi_percentage}%`
                            : "-"}
                        </TableCell>
                        <TableCell className="text-muted-foreground">
                          {new Date(record.created_at).toLocaleDateString("zh-CN")}
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              )}
            </CardContent>
          </Card>
        </>
      )}
    </div>
  );
}
