import React from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Progress } from "@/components/ui/progress";
import { 
  TrendingUp, DollarSign, Calendar, Target, 
  ArrowRight, CheckCircle, Sparkles, BarChart3,
  Clock, Users, Zap, ArrowUpRight
} from "lucide-react";
import { LineChart, Line, AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, BarChart, Bar, Legend } from "recharts";

export default function PredictiveSavingsModel({ metrics, projections, assignments, rates, userRole }) {
  // Generate forecast data
  const forecastData = [
    { month: "Jan", current: 45000, optimized: 38000, savings: 7000 },
    { month: "Feb", current: 48000, optimized: 40000, savings: 8000 },
    { month: "Mar", current: 52000, optimized: 42000, savings: 10000 },
    { month: "Apr", current: 50000, optimized: 40000, savings: 10000 },
    { month: "May", current: 55000, optimized: 43000, savings: 12000 },
    { month: "Jun", current: 58000, optimized: 45000, savings: 13000 },
    { month: "Jul", current: 62000, optimized: 47000, savings: 15000 },
    { month: "Aug", current: 60000, optimized: 46000, savings: 14000 },
    { month: "Sep", current: 55000, optimized: 43000, savings: 12000 },
    { month: "Oct", current: 58000, optimized: 45000, savings: 13000 },
    { month: "Nov", current: 65000, optimized: 50000, savings: 15000 },
    { month: "Dec", current: 70000, optimized: 53000, savings: 17000 },
  ];

  const savingsStrategies = [
    {
      id: 1,
      strategy: "Shift to Higher-Performing Vendors",
      impact: "High",
      savingsPercent: 12,
      timeToImplement: "2-4 weeks",
      confidence: 92,
      description: "Consolidate spend with top-tier vendors who offer better rates and reliability",
    },
    {
      id: 2,
      strategy: "Contracted Pricing Negotiation",
      impact: "High",
      savingsPercent: 15,
      timeToImplement: "4-6 weeks",
      confidence: 88,
      description: "Lock in volume discounts with preferred supplier agreements",
    },
    {
      id: 3,
      strategy: "Internal Workforce Pool",
      impact: "Medium",
      savingsPercent: 8,
      timeToImplement: "6-8 weeks",
      confidence: 85,
      description: "Build internal pool for recurring needs, reducing agency fees",
    },
    {
      id: 4,
      strategy: "Skill-Matched Talent",
      impact: "Medium",
      savingsPercent: 6,
      timeToImplement: "2-3 weeks",
      confidence: 90,
      description: "Match worker skills to job requirements, reducing overtime and rework",
    },
  ];

  const scenarioData = [
    { scenario: "Conservative", savings: projections.year * 0.7 },
    { scenario: "Moderate", savings: projections.year },
    { scenario: "Aggressive", savings: projections.year * 1.4 },
  ];

  return (
    <div className="space-y-6">
      {/* Predictive Header */}
      <Card className="bg-gradient-to-r from-purple-600 to-indigo-600 text-white border-0">
        <CardContent className="p-6">
          <div className="flex items-center gap-3 mb-4">
            <div className="w-12 h-12 bg-white/20 rounded-xl flex items-center justify-center">
              <Sparkles className="w-6 h-6 text-white" />
            </div>
            <div>
              <h3 className="text-xl font-bold">AI-Powered Savings Forecast</h3>
              <p className="text-purple-200">Predictive analysis based on your workforce data</p>
            </div>
          </div>
          <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mt-4">
            {[
              { label: "7-Day Forecast", value: projections.sevenDays },
              { label: "30-Day Forecast", value: projections.thirtyDays },
              { label: "Quarterly Forecast", value: projections.quarter },
              { label: "Annual Forecast", value: projections.year },
            ].map((item, idx) => (
              <div key={idx} className="bg-white/10 rounded-lg p-4">
                <p className="text-purple-200 text-sm">{item.label}</p>
                <p className="text-2xl font-bold">${item.value.toLocaleString(undefined, { maximumFractionDigits: 0 })}</p>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>

      {/* Forecast Chart */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <TrendingUp className="w-5 h-5 text-green-500" />
              12-Month Savings Projection
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="h-80">
              <ResponsiveContainer width="100%" height="100%">
                <AreaChart data={forecastData}>
                  <defs>
                    <linearGradient id="colorCurrent" x1="0" y1="0" x2="0" y2="1">
                      <stop offset="5%" stopColor="#ef4444" stopOpacity={0.3}/>
                      <stop offset="95%" stopColor="#ef4444" stopOpacity={0}/>
                    </linearGradient>
                    <linearGradient id="colorOptimized" x1="0" y1="0" x2="0" y2="1">
                      <stop offset="5%" stopColor="#22c55e" stopOpacity={0.3}/>
                      <stop offset="95%" stopColor="#22c55e" stopOpacity={0}/>
                    </linearGradient>
                  </defs>
                  <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" />
                  <XAxis dataKey="month" stroke="#64748b" fontSize={12} />
                  <YAxis stroke="#64748b" fontSize={12} tickFormatter={(v) => `$${(v/1000).toFixed(0)}k`} />
                  <Tooltip 
                    formatter={(value) => [`$${value.toLocaleString()}`, '']}
                    contentStyle={{ background: 'white', border: '1px solid #e2e8f0', borderRadius: '8px' }}
                  />
                  <Legend />
                  <Area type="monotone" dataKey="current" stroke="#ef4444" fill="url(#colorCurrent)" name="Current Spend" />
                  <Area type="monotone" dataKey="optimized" stroke="#22c55e" fill="url(#colorOptimized)" name="Optimized Spend" />
                </AreaChart>
              </ResponsiveContainer>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <BarChart3 className="w-5 h-5 text-blue-500" />
              Monthly Savings Breakdown
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="h-80">
              <ResponsiveContainer width="100%" height="100%">
                <BarChart data={forecastData}>
                  <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" />
                  <XAxis dataKey="month" stroke="#64748b" fontSize={12} />
                  <YAxis stroke="#64748b" fontSize={12} tickFormatter={(v) => `$${(v/1000).toFixed(0)}k`} />
                  <Tooltip 
                    formatter={(value) => [`$${value.toLocaleString()}`, 'Savings']}
                    contentStyle={{ background: 'white', border: '1px solid #e2e8f0', borderRadius: '8px' }}
                  />
                  <Bar dataKey="savings" fill="#0A39DF" radius={[4, 4, 0, 0]} name="Savings" />
                </BarChart>
              </ResponsiveContainer>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Savings Strategies */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Target className="w-5 h-5 text-amber-500" />
            Recommended Savings Strategies
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            {savingsStrategies.map((strategy) => (
              <div key={strategy.id} className="p-4 bg-slate-50 rounded-xl border border-slate-200 hover:shadow-md transition-all">
                <div className="flex items-start justify-between mb-3">
                  <div>
                    <div className="flex items-center gap-2 mb-1">
                      <h4 className="font-semibold text-slate-900">{strategy.strategy}</h4>
                      <Badge className={strategy.impact === "High" ? "bg-red-100 text-red-700" : "bg-amber-100 text-amber-700"}>
                        {strategy.impact} Impact
                      </Badge>
                    </div>
                    <p className="text-sm text-slate-600">{strategy.description}</p>
                  </div>
                  <div className="text-right">
                    <p className="text-2xl font-bold text-green-600">+{strategy.savingsPercent}%</p>
                    <p className="text-xs text-slate-500">potential savings</p>
                  </div>
                </div>
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-4 text-sm">
                    <div className="flex items-center gap-1 text-slate-500">
                      <Clock className="w-4 h-4" />
                      {strategy.timeToImplement}
                    </div>
                    <div className="flex items-center gap-1 text-slate-500">
                      <CheckCircle className="w-4 h-4 text-green-500" />
                      {strategy.confidence}% confidence
                    </div>
                  </div>
                  <Button size="sm" className="bg-[#0A39DF] hover:bg-[#0831b8]" onClick={() => alert(`Implementing: ${strategy.strategy}`)}>
                    Implement
                    <ArrowRight className="w-4 h-4 ml-1" />
                  </Button>
                </div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>

      {/* Scenario Comparison */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Zap className="w-5 h-5 text-yellow-500" />
            Scenario Analysis
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            {scenarioData.map((scenario, idx) => (
              <div 
                key={idx} 
                className={`p-6 rounded-xl border-2 text-center ${
                  idx === 1 
                    ? "bg-[#0A39DF] text-white border-[#0A39DF]" 
                    : "bg-white border-slate-200"
                }`}
              >
                <p className={`text-sm font-medium mb-2 ${idx === 1 ? "text-blue-200" : "text-slate-500"}`}>
                  {scenario.scenario}
                </p>
                <p className={`text-3xl font-bold ${idx === 1 ? "text-white" : "text-slate-900"}`}>
                  ${scenario.savings.toLocaleString(undefined, { maximumFractionDigits: 0 })}
                </p>
                <p className={`text-sm mt-1 ${idx === 1 ? "text-blue-200" : "text-slate-500"}`}>
                  annual savings
                </p>
                {idx === 1 && (
                  <Badge className="mt-3 bg-white/20 text-white border-0">
                    Recommended
                  </Badge>
                )}
              </div>
            ))}
          </div>
        </CardContent>
      </Card>
    </div>
  );
}