'use client';

import { useCallback, useEffect, useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Skeleton } from '@/components/ui/skeleton';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Button } from '@/components/ui/button';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Activity,
  TrendingUp,
  TrendingDown,
  Minus,
  Users,
  Zap,
  DollarSign,
  Shield,
  AlertTriangle,
  ArrowRight,
  RefreshCw,
} from 'lucide-react';
import Link from 'next/link';
import {
  getProductHealth,
  type ProductHealth,
  type HealthDimension,
} from '@/lib/predictive-client';

interface HealthScoreCardProps {
  title: string;
  dimension: HealthDimension;
  icon: React.ReactNode;
}

function HealthScoreCard({ title, dimension, icon }: HealthScoreCardProps) {
  const getScoreColor = (score: number) => {
    if (score >= 80) return 'text-green-500';
    if (score >= 60) return 'text-yellow-500';
    return 'text-red-500';
  };

  const getTrendIcon = (trend: string) => {
    switch (trend) {
      case 'improving':
        return <TrendingUp className="h-4 w-4 text-green-500" />;
      case 'declining':
        return <TrendingDown className="h-4 w-4 text-red-500" />;
      default:
        return <Minus className="h-4 w-4 text-gray-400" />;
    }
  };

  return (
    <Card>
      <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
        <CardTitle className="text-sm font-medium">{title}</CardTitle>
        {icon}
      </CardHeader>
      <CardContent>
        <div className="flex items-baseline space-x-2">
          <span className={`text-2xl font-bold ${getScoreColor(dimension.score)}`}>
            {dimension.score}
          </span>
          <span className="text-sm text-muted-foreground">/100</span>
        </div>
        <div className="mt-2 flex items-center space-x-2">
          {getTrendIcon(dimension.trend)}
          <span className="text-xs text-muted-foreground capitalize">{dimension.trend}</span>
        </div>
        {Object.entries(dimension.metrics)
          .slice(0, 2)
          .map(([key, value]) => (
            <div key={key} className="mt-1 text-xs text-muted-foreground">
              {key}: {typeof value === 'number' ? value.toFixed(1) : value}
            </div>
          ))}
      </CardContent>
    </Card>
  );
}

export default function HealthDashboardPage() {
  const [healthData, setHealthData] = useState<ProductHealth[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [selectedProduct, setSelectedProduct] = useState<string>('all');

  const loadHealthData = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);
      const data = await getProductHealth(selectedProduct === 'all' ? undefined : selectedProduct);
      setHealthData(data);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load health data');
    } finally {
      setLoading(false);
    }
  }, [selectedProduct]);

  useEffect(() => {
    void loadHealthData();
  }, [loadHealthData]);

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'healthy':
        return <Badge className="bg-green-500">Healthy</Badge>;
      case 'warning':
        return <Badge className="bg-yellow-500">Warning</Badge>;
      case 'critical':
        return <Badge className="bg-red-500">Critical</Badge>;
      default:
        return <Badge variant="secondary">{status}</Badge>;
    }
  };

  const latestHealth = healthData[0];

  if (loading) {
    return (
      <div className="space-y-6 p-6">
        <Skeleton className="h-8 w-64" />
        <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
          {Array.from({ length: 6 }).map((_, i) => (
            <Skeleton key={i} className="h-40" />
          ))}
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="space-y-6 p-6">
        <Alert variant="destructive">
          <AlertTriangle className="h-4 w-4" />
          <AlertDescription>{error}</AlertDescription>
        </Alert>
        <Button onClick={loadHealthData}>
          <RefreshCw className="mr-2 h-4 w-4" />
          Retry
        </Button>
      </div>
    );
  }

  return (
    <div className="space-y-6 p-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">Product Health Dashboard</h1>
          <p className="text-muted-foreground">
            Monitor product health across 6 dimensions with ML-powered predictions
          </p>
        </div>
        <div className="flex items-center gap-4">
          <Select value={selectedProduct} onValueChange={setSelectedProduct}>
            <SelectTrigger className="w-40">
              <SelectValue placeholder="Select product" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">All Products</SelectItem>
              <SelectItem value="lysnrai">LysnrAI</SelectItem>
              <SelectItem value="chronomind">ChronoMind</SelectItem>
              <SelectItem value="mindlyst">MindLyst</SelectItem>
              <SelectItem value="jarvisjr">JarvisJr</SelectItem>
              <SelectItem value="nomgap">NomGap</SelectItem>
              <SelectItem value="peakpulse">PeakPulse</SelectItem>
            </SelectContent>
          </Select>
          <Button onClick={loadHealthData} variant="outline" size="icon">
            <RefreshCw className="h-4 w-4" />
          </Button>
        </div>
      </div>

      {latestHealth && (
        <>
          {/* Overall Health */}
          <Card className={latestHealth.healthStatus === 'critical' ? 'border-red-500' : undefined}>
            <CardHeader>
              <div className="flex items-center justify-between">
                <div>
                  <CardTitle className="flex items-center gap-2">
                    <Activity className="h-5 w-5" />
                    Overall Health Score
                  </CardTitle>
                  <CardDescription>
                    {latestHealth.productId} — Last updated:{' '}
                    {new Date(latestHealth.date).toLocaleDateString()}
                  </CardDescription>
                </div>
                <div className="flex items-center gap-4">
                  <div className="text-right">
                    <div className="text-4xl font-bold">{latestHealth.overallHealthScore}</div>
                    <div className="text-sm text-muted-foreground">/100</div>
                  </div>
                  {getStatusBadge(latestHealth.healthStatus)}
                </div>
              </div>
            </CardHeader>
            <CardContent>
              <div className="flex items-center gap-4 text-sm">
                <div className="flex items-center gap-1">
                  <span className="text-muted-foreground">vs 7d:</span>
                  <span
                    className={latestHealth.vsBaseline7Day >= 0 ? 'text-green-500' : 'text-red-500'}
                  >
                    {latestHealth.vsBaseline7Day >= 0 ? '+' : ''}
                    {latestHealth.vsBaseline7Day.toFixed(1)}%
                  </span>
                </div>
                <div className="flex items-center gap-1">
                  <span className="text-muted-foreground">vs 30d:</span>
                  <span
                    className={
                      latestHealth.vsBaseline30Day >= 0 ? 'text-green-500' : 'text-red-500'
                    }
                  >
                    {latestHealth.vsBaseline30Day >= 0 ? '+' : ''}
                    {latestHealth.vsBaseline30Day.toFixed(1)}%
                  </span>
                </div>
              </div>
              {latestHealth.forecasts && (
                <div className="mt-4 flex items-center gap-8 text-sm">
                  <div>
                    <span className="text-muted-foreground">Next 7 days:</span>{' '}
                    <span className="font-medium">
                      {latestHealth.forecasts.next7Days.expectedHealthScore}
                    </span>
                    <span className="text-muted-foreground">
                      {' '}
                      (±
                      {(
                        (latestHealth.forecasts.next7Days.confidenceInterval[1] -
                          latestHealth.forecasts.next7Days.confidenceInterval[0]) /
                        2
                      ).toFixed(1)}
                      )
                    </span>
                  </div>
                  <div>
                    <span className="text-muted-foreground">Next 30 days:</span>{' '}
                    <span className="font-medium">
                      {latestHealth.forecasts.next30Days.expectedHealthScore}
                    </span>
                    <span className="text-muted-foreground">
                      {' '}
                      (±
                      {(
                        (latestHealth.forecasts.next30Days.confidenceInterval[1] -
                          latestHealth.forecasts.next30Days.confidenceInterval[0]) /
                        2
                      ).toFixed(1)}
                      )
                    </span>
                  </div>
                </div>
              )}
            </CardContent>
          </Card>

          {/* Dimension Cards */}
          <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
            <HealthScoreCard
              title="Acquisition"
              dimension={latestHealth.dimensions.acquisition}
              icon={<Users className="h-4 w-4 text-blue-500" />}
            />
            <HealthScoreCard
              title="Activation"
              dimension={latestHealth.dimensions.activation}
              icon={<Zap className="h-4 w-4 text-yellow-500" />}
            />
            <HealthScoreCard
              title="Retention"
              dimension={latestHealth.dimensions.retention}
              icon={<TrendingUp className="h-4 w-4 text-green-500" />}
            />
            <HealthScoreCard
              title="Engagement"
              dimension={latestHealth.dimensions.engagement}
              icon={<Activity className="h-4 w-4 text-purple-500" />}
            />
            <HealthScoreCard
              title="Revenue"
              dimension={latestHealth.dimensions.revenue}
              icon={<DollarSign className="h-4 w-4 text-emerald-500" />}
            />
            <HealthScoreCard
              title="Stability"
              dimension={latestHealth.dimensions.stability}
              icon={<Shield className="h-4 w-4 text-indigo-500" />}
            />
          </div>

          {/* Anomalies */}
          {latestHealth.anomalies && latestHealth.anomalies.length > 0 && (
            <Card className="border-red-200">
              <CardHeader>
                <CardTitle className="flex items-center gap-2 text-red-600">
                  <AlertTriangle className="h-5 w-5" />
                  Detected Anomalies ({latestHealth.anomalies.length})
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-2">
                  {latestHealth.anomalies.map((anomaly, idx) => (
                    <div
                      key={idx}
                      className="flex items-center justify-between rounded-lg border p-3"
                    >
                      <div>
                        <div className="font-medium">{anomaly.metric}</div>
                        <div className="text-sm text-muted-foreground">
                          Expected: {anomaly.expectedValue.toFixed(2)} • Actual:{' '}
                          {anomaly.actualValue.toFixed(2)}
                        </div>
                        {anomaly.suggestedCause && (
                          <div className="text-xs text-muted-foreground mt-1">
                            Suggested cause: {anomaly.suggestedCause}
                          </div>
                        )}
                      </div>
                      <Badge variant={anomaly.severity === 'critical' ? 'destructive' : 'default'}>
                        {anomaly.deviationPercent > 0 ? '+' : ''}
                        {anomaly.deviationPercent.toFixed(1)}%
                      </Badge>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>
          )}

          {/* Navigation */}
          <div className="flex gap-4">
            <Link href="/predictive/at-risk">
              <Button variant="outline" className="gap-2">
                View At-Risk Users
                <ArrowRight className="h-4 w-4" />
              </Button>
            </Link>
            <Link href="/predictive/campaigns">
              <Button variant="outline" className="gap-2">
                Manage Retention Campaigns
                <ArrowRight className="h-4 w-4" />
              </Button>
            </Link>
          </div>
        </>
      )}

      {!latestHealth && !loading && (
        <Alert>
          <AlertDescription>
            No health data available. Health scores are computed daily from telemetry data.
          </AlertDescription>
        </Alert>
      )}
    </div>
  );
}
