"use client";

import { useEffect, useState } from "react";
import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Progress } from "@/components/ui/progress";
import { useToast } from "@/hooks/use-toast";
import {
  Brain,
  TrendingUp,
  TrendingDown,
  Target,
  AlertTriangle,
  Phone,
  MessageSquare,
  Mail,
  Users,
  RefreshCw,
  Lightbulb,
  Eye,
  ArrowRight,
  BarChart3,
  PieChart,
  Clock,
} from "lucide-react";
import { ProtectedLayout } from "@/components/protected-layout";
import {
  PieChart as RechartsPie,
  Pie,
  Cell,
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
} from "recharts";

interface PriorityFile {
  id: string;
  customerName: string;
  phoneNumber: string;
  outstandingBalance: number;
  paymentProbability: number;
  riskLevel: string;
  optimalChannel: string | null;
  nextBestAction: string;
  agent: string;
}

interface Analytics {
  summary: {
    totalPredictions: number;
    avgPaymentProbability: number;
    totalFeedbackRecords: number;
    overallSuccessRate: number;
  };
  riskDistribution: { HIGH: number; MEDIUM: number; LOW: number };
  channelDistribution: { [key: string]: number };
  timeDistribution: { [key: string]: number };
  actionEffectivenessRates: { [key: string]: number };
  priorityFiles: PriorityFile[];
  atRiskFiles: PriorityFile[];
  learningInsights: string[];
}

const COLORS = {
  HIGH: "#ef4444",
  MEDIUM: "#f59e0b",
  LOW: "#22c55e",
};

const CHANNEL_COLORS = {
  CALL: "#3b82f6",
  SMS: "#10b981",
  EMAIL: "#8b5cf6",
  VISIT: "#f59e0b",
};

export default function AIAnalyticsPage() {
  const router = useRouter();
  const { toast } = useToast();
  const { data: session, status } = useSession() || {};
  const [analytics, setAnalytics] = useState<Analytics | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isGenerating, setIsGenerating] = useState(false);

  useEffect(() => {
    if (status === "unauthenticated") {
      router.push("/login");
    } else if (status === "authenticated") {
      fetchAnalytics();
    }
  }, [status]);

  const fetchAnalytics = async () => {
    try {
      setIsLoading(true);
      const res = await fetch("/api/ai/analytics");
      if (res.ok) {
        const data = await res.json();
        setAnalytics(data);
      }
    } catch (error) {
      console.error("Error fetching AI analytics:", error);
      toast({
        title: "Error",
        description: "Failed to fetch AI analytics",
        variant: "destructive",
      });
    } finally {
      setIsLoading(false);
    }
  };

  const generateBatchPredictions = async () => {
    try {
      setIsGenerating(true);
      toast({
        title: "Generating Predictions",
        description: "This may take a few minutes for large datasets...",
      });

      // Fetch all files first
      const filesRes = await fetch("/api/collection-files?limit=100");
      if (!filesRes.ok) throw new Error("Failed to fetch files");
      const filesData = await filesRes.json();
      const files = filesData.files || [];

      // Generate predictions for each file (limit to prevent timeout)
      let generated = 0;
      for (const file of files.slice(0, 20)) {
        try {
          await fetch(`/api/ai/predictions?fileId=${file.id}&refresh=true`);
          generated++;
        } catch (e) {
          console.error(`Failed to generate prediction for ${file.id}`);
        }
      }

      toast({
        title: "Success",
        description: `Generated ${generated} AI predictions`,
      });
      fetchAnalytics();
    } catch (error) {
      toast({
        title: "Error",
        description: "Failed to generate predictions",
        variant: "destructive",
      });
    } finally {
      setIsGenerating(false);
    }
  };

  const formatCurrency = (amount: number) => {
    return `Ksh ${amount.toLocaleString()}`;
  };

  const getChannelIcon = (channel: string | null) => {
    switch (channel) {
      case "CALL":
        return <Phone className="h-4 w-4" />;
      case "SMS":
        return <MessageSquare className="h-4 w-4" />;
      case "EMAIL":
        return <Mail className="h-4 w-4" />;
      default:
        return <Users className="h-4 w-4" />;
    }
  };

  // Prepare chart data
  const riskChartData = analytics
    ? [
        { name: "High Risk", value: analytics.riskDistribution.HIGH, color: COLORS.HIGH },
        { name: "Medium Risk", value: analytics.riskDistribution.MEDIUM, color: COLORS.MEDIUM },
        { name: "Low Risk", value: analytics.riskDistribution.LOW, color: COLORS.LOW },
      ].filter((d) => d.value > 0)
    : [];

  const channelChartData = analytics
    ? Object.entries(analytics.channelDistribution).map(([key, value]) => ({
        name: key,
        count: value,
        fill: CHANNEL_COLORS[key as keyof typeof CHANNEL_COLORS] || "#6b7280",
      }))
    : [];

  const effectivenessChartData = analytics
    ? Object.entries(analytics.actionEffectivenessRates).map(([key, value]) => ({
        name: key,
        rate: Math.round(value),
        fill: CHANNEL_COLORS[key as keyof typeof CHANNEL_COLORS] || "#6b7280",
      }))
    : [];

  if (status === "loading" || isLoading) {
    return (
      <ProtectedLayout>
        <div className="flex h-96 items-center justify-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-purple-600"></div>
        </div>
      </ProtectedLayout>
    );
  }

  return (
    <ProtectedLayout>
      <div className="space-y-6">
        {/* Header */}
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-2xl font-bold flex items-center gap-2">
              <Brain className="h-7 w-7 text-purple-600" />
              AI Analytics & Predictions
            </h1>
            <p className="text-gray-500">Predictive insights to optimize your collection strategy</p>
          </div>
          <Button
            onClick={generateBatchPredictions}
            disabled={isGenerating}
            className="bg-purple-600 hover:bg-purple-700"
          >
            {isGenerating ? (
              <RefreshCw className="h-4 w-4 mr-2 animate-spin" />
            ) : (
              <Brain className="h-4 w-4 mr-2" />
            )}
            Generate Predictions
          </Button>
        </div>

        {/* Summary Cards */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          <Card className="bg-gradient-to-br from-purple-500 to-purple-600 text-white">
            <CardContent className="pt-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-purple-100 text-sm">Total Predictions</p>
                  <p className="text-3xl font-bold">{analytics?.summary.totalPredictions || 0}</p>
                </div>
                <Brain className="h-10 w-10 text-purple-200" />
              </div>
            </CardContent>
          </Card>

          <Card className="bg-gradient-to-br from-green-500 to-green-600 text-white">
            <CardContent className="pt-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-green-100 text-sm">Avg Payment Probability</p>
                  <p className="text-3xl font-bold">{analytics?.summary.avgPaymentProbability || 0}%</p>
                </div>
                <TrendingUp className="h-10 w-10 text-green-200" />
              </div>
            </CardContent>
          </Card>

          <Card className="bg-gradient-to-br from-blue-500 to-blue-600 text-white">
            <CardContent className="pt-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-blue-100 text-sm">Feedback Records</p>
                  <p className="text-3xl font-bold">{analytics?.summary.totalFeedbackRecords || 0}</p>
                </div>
                <BarChart3 className="h-10 w-10 text-blue-200" />
              </div>
            </CardContent>
          </Card>

          <Card className="bg-gradient-to-br from-amber-500 to-amber-600 text-white">
            <CardContent className="pt-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-amber-100 text-sm">Success Rate</p>
                  <p className="text-3xl font-bold">{analytics?.summary.overallSuccessRate || 0}%</p>
                </div>
                <Target className="h-10 w-10 text-amber-200" />
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Charts Row */}
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {/* Risk Distribution */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <PieChart className="h-5 w-5 text-purple-500" />
                Risk Distribution
              </CardTitle>
              <CardDescription>Customer risk levels based on AI analysis</CardDescription>
            </CardHeader>
            <CardContent>
              {riskChartData.length > 0 ? (
                <ResponsiveContainer width="100%" height={200}>
                  <RechartsPie>
                    <Pie
                      data={riskChartData}
                      cx="50%"
                      cy="50%"
                      innerRadius={50}
                      outerRadius={80}
                      paddingAngle={5}
                      dataKey="value"
                    >
                      {riskChartData.map((entry, index) => (
                        <Cell key={`cell-${index}`} fill={entry.color} />
                      ))}
                    </Pie>
                    <Tooltip />
                    <Legend />
                  </RechartsPie>
                </ResponsiveContainer>
              ) : (
                <div className="h-48 flex items-center justify-center text-gray-500">
                  No data available
                </div>
              )}
            </CardContent>
          </Card>

          {/* Channel Distribution */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <BarChart3 className="h-5 w-5 text-blue-500" />
                Optimal Channels
              </CardTitle>
              <CardDescription>Recommended engagement channels</CardDescription>
            </CardHeader>
            <CardContent>
              {channelChartData.length > 0 ? (
                <ResponsiveContainer width="100%" height={200}>
                  <BarChart data={channelChartData}>
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis dataKey="name" />
                    <YAxis />
                    <Tooltip />
                    <Bar dataKey="count" fill="#8884d8">
                      {channelChartData.map((entry, index) => (
                        <Cell key={`cell-${index}`} fill={entry.fill} />
                      ))}
                    </Bar>
                  </BarChart>
                </ResponsiveContainer>
              ) : (
                <div className="h-48 flex items-center justify-center text-gray-500">
                  No data available
                </div>
              )}
            </CardContent>
          </Card>

          {/* Action Effectiveness */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Target className="h-5 w-5 text-green-500" />
                Action Effectiveness
              </CardTitle>
              <CardDescription>Success rates by action type</CardDescription>
            </CardHeader>
            <CardContent>
              {effectivenessChartData.length > 0 ? (
                <ResponsiveContainer width="100%" height={200}>
                  <BarChart data={effectivenessChartData} layout="vertical">
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis type="number" domain={[0, 100]} />
                    <YAxis type="category" dataKey="name" />
                    <Tooltip formatter={(value) => `${value}%`} />
                    <Bar dataKey="rate" fill="#22c55e">
                      {effectivenessChartData.map((entry, index) => (
                        <Cell key={`cell-${index}`} fill={entry.fill} />
                      ))}
                    </Bar>
                  </BarChart>
                </ResponsiveContainer>
              ) : (
                <div className="h-48 flex items-center justify-center text-gray-500">
                  Record feedback to see effectiveness
                </div>
              )}
            </CardContent>
          </Card>
        </div>

        {/* Learning Insights */}
        {analytics?.learningInsights && analytics.learningInsights.length > 0 && (
          <Card className="border-purple-200 bg-gradient-to-r from-purple-50 to-white">
            <CardHeader>
              <CardTitle className="flex items-center gap-2 text-purple-700">
                <Lightbulb className="h-5 w-5" />
                AI Learning Insights
              </CardTitle>
              <CardDescription>Patterns and insights learned from recorded outcomes</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                {analytics.learningInsights.map((insight, index) => (
                  <div
                    key={index}
                    className="bg-white p-4 rounded-lg border border-purple-100 flex items-start gap-3"
                  >
                    <div className="bg-purple-100 p-2 rounded-full">
                      <Lightbulb className="h-4 w-4 text-purple-600" />
                    </div>
                    <p className="text-sm text-gray-700">{insight}</p>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        )}

        {/* Priority Files */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {/* High Priority (Likely to Pay) */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2 text-green-700">
                <TrendingUp className="h-5 w-5" />
                High Priority - Likely to Pay
              </CardTitle>
              <CardDescription>Customers with high payment probability - prioritize these</CardDescription>
            </CardHeader>
            <CardContent>
              {analytics?.priorityFiles && analytics.priorityFiles.length > 0 ? (
                <div className="space-y-3">
                  {analytics.priorityFiles.map((file) => (
                    <div
                      key={file.id}
                      className="flex items-center justify-between p-3 bg-green-50 rounded-lg border border-green-100"
                    >
                      <div className="flex-1">
                        <div className="flex items-center gap-2">
                          <p className="font-medium">{file.customerName}</p>
                          <Badge className="bg-green-100 text-green-800">
                            {file.paymentProbability}%
                          </Badge>
                        </div>
                        <p className="text-sm text-gray-500">{formatCurrency(file.outstandingBalance)}</p>
                        <div className="flex items-center gap-2 mt-1">
                          {getChannelIcon(file.optimalChannel)}
                          <span className="text-xs text-gray-500">
                            Best via {file.optimalChannel || "Any"}
                          </span>
                        </div>
                      </div>
                      <Link href={`/files/${file.id}`}>
                        <Button variant="ghost" size="sm">
                          <Eye className="h-4 w-4 mr-1" />
                          View
                        </Button>
                      </Link>
                    </div>
                  ))}
                </div>
              ) : (
                <div className="text-center py-8 text-gray-500">
                  <TrendingUp className="h-12 w-12 mx-auto mb-2 opacity-30" />
                  <p>Generate predictions to see priority files</p>
                </div>
              )}
            </CardContent>
          </Card>

          {/* At Risk Files */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2 text-red-700">
                <AlertTriangle className="h-5 w-5" />
                At Risk - Needs Attention
              </CardTitle>
              <CardDescription>High balance customers with low payment probability</CardDescription>
            </CardHeader>
            <CardContent>
              {analytics?.atRiskFiles && analytics.atRiskFiles.length > 0 ? (
                <div className="space-y-3">
                  {analytics.atRiskFiles.map((file) => (
                    <div
                      key={file.id}
                      className="flex items-center justify-between p-3 bg-red-50 rounded-lg border border-red-100"
                    >
                      <div className="flex-1">
                        <div className="flex items-center gap-2">
                          <p className="font-medium">{file.customerName}</p>
                          <Badge variant="destructive">
                            {file.paymentProbability}% risk
                          </Badge>
                        </div>
                        <p className="text-sm text-red-600 font-medium">
                          {formatCurrency(file.outstandingBalance)}
                        </p>
                        <p className="text-xs text-gray-500 mt-1">
                          {file.nextBestAction}
                        </p>
                      </div>
                      <Link href={`/files/${file.id}`}>
                        <Button variant="ghost" size="sm">
                          <Eye className="h-4 w-4 mr-1" />
                          View
                        </Button>
                      </Link>
                    </div>
                  ))}
                </div>
              ) : (
                <div className="text-center py-8 text-gray-500">
                  <AlertTriangle className="h-12 w-12 mx-auto mb-2 opacity-30" />
                  <p>Generate predictions to identify at-risk files</p>
                </div>
              )}
            </CardContent>
          </Card>
        </div>

        {/* Optimal Timing */}
        {analytics?.timeDistribution && Object.keys(analytics.timeDistribution).length > 0 && (
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Clock className="h-5 w-5 text-blue-500" />
                Optimal Engagement Times
              </CardTitle>
              <CardDescription>Best times to contact customers based on AI analysis</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-3 gap-4">
                {Object.entries(analytics.timeDistribution).map(([time, count]) => (
                  <div
                    key={time}
                    className="text-center p-4 bg-blue-50 rounded-lg border border-blue-100"
                  >
                    <p className="text-lg font-bold text-blue-700">{time}</p>
                    <p className="text-sm text-gray-500">{count} customers</p>
                    <Progress
                      value={(count / Math.max(...Object.values(analytics.timeDistribution))) * 100}
                      className="mt-2 h-2"
                    />
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        )}
      </div>
    </ProtectedLayout>
  );
}
