import React from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Download, TrendingUp, Users, Star, Heart, AlertTriangle, ArrowUp } from "lucide-react";
import { LineChart, Line, BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from "recharts";
import { Badge } from "@/components/ui/badge";
import { useToast } from "@/components/ui/use-toast";
import ReportInsightsBanner from "./ReportInsightsBanner";

export default function ClientTrendsReport({ events, invoices, userRole = 'admin' }) {
  const { toast } = useToast();

  // Bookings by month
  const bookingsByMonth = events.reduce((acc, event) => {
    if (!event.date) return acc;
    const date = new Date(event.date);
    const month = date.toLocaleString('default', { month: 'short' });
    acc[month] = (acc[month] || 0) + 1;
    return acc;
  }, {});

  const monthlyBookings = Object.entries(bookingsByMonth).map(([month, count]) => ({
    month,
    bookings: count,
  }));

  // Top clients by booking count
  const clientBookings = events.reduce((acc, event) => {
    const client = event.business_name || 'Unknown';
    if (!acc[client]) {
      acc[client] = { name: client, bookings: 0, revenue: 0 };
    }
    acc[client].bookings += 1;
    acc[client].revenue += event.total || 0;
    return acc;
  }, {});

  const topClients = Object.values(clientBookings)
    .sort((a, b) => b.bookings - a.bookings)
    .slice(0, 10);

  // Client satisfaction (mock data - would come from feedback)
  const avgSatisfaction = 4.6;
  const totalClients = new Set(events.map(e => e.business_name).filter(Boolean)).size;
  const repeatRate = ((events.filter(e => e.is_recurring).length / events.length) * 100).toFixed(1);

  const handleExport = () => {
    const csv = [
      ['Client Trends Report'],
      ['Generated', new Date().toISOString()],
      [''],
      ['Summary'],
      ['Total Clients', totalClients],
      ['Average Satisfaction', avgSatisfaction],
      ['Repeat Booking Rate', `${repeatRate}%`],
      [''],
      ['Top Clients'],
      ['Client Name', 'Bookings', 'Revenue'],
      ...topClients.map(c => [c.name, c.bookings, c.revenue.toFixed(2)]),
      [''],
      ['Monthly Bookings'],
      ['Month', 'Bookings'],
      ...monthlyBookings.map(m => [m.month, m.bookings]),
    ].map(row => row.join(',')).join('\n');

    const blob = new Blob([csv], { type: 'text/csv' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `client-trends-${new Date().toISOString().split('T')[0]}.csv`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);

    toast({ title: "✅ Report Exported", description: "Client trends report downloaded as CSV" });
  };

  // Churn risk
  const lowEngagementClients = topClients.filter(c => c.bookings < 3);

  return (
    <div className="space-y-6">
      {/* AI Insights Banner */}
      <ReportInsightsBanner userRole={userRole} reportType="clients" />

      <div className="flex justify-between items-center">
        <div>
          <h2 className="text-xl font-bold text-slate-900">Client Intelligence</h2>
          <p className="text-sm text-slate-500">Satisfaction, retention & growth opportunities</p>
        </div>
        <Button onClick={handleExport} size="sm" className="bg-[#0A39DF]">
          <Download className="w-4 h-4 mr-1" />
          Export
        </Button>
      </div>

      {/* Retention Alert */}
      {lowEngagementClients.length > 0 && (
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div className="bg-red-50 border border-red-200 rounded-lg p-3 flex items-center justify-between">
            <div className="flex items-center gap-2">
              <AlertTriangle className="w-5 h-5 text-red-600" />
              <div>
                <span className="text-sm font-medium text-red-800">{lowEngagementClients.length} clients at churn risk</span>
                <p className="text-xs text-red-600">Less than 3 bookings this period</p>
              </div>
            </div>
            <Button size="sm" variant="outline" className="border-red-300 text-red-700 hover:bg-red-100">
              View List
            </Button>
          </div>
          <div className="bg-green-50 border border-green-200 rounded-lg p-3 flex items-center justify-between">
            <div className="flex items-center gap-2">
              <Heart className="w-5 h-5 text-green-600" />
              <div>
                <span className="text-sm font-medium text-green-800">{topClients.filter(c => c.bookings >= 5).length} loyal clients</span>
                <p className="text-xs text-green-600">5+ bookings — eligible for rewards</p>
              </div>
            </div>
            <Button size="sm" variant="outline" className="border-green-300 text-green-700 hover:bg-green-100">
              Send Thank You
            </Button>
          </div>
        </div>
      )}

      {/* Decision Cards */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card className="border-l-4 border-l-blue-500">
          <CardContent className="pt-4 pb-3">
            <p className="text-xs text-slate-500 uppercase tracking-wider">Total Clients</p>
            <p className="text-2xl font-bold text-slate-900">{totalClients}</p>
            <p className="text-xs text-slate-500 mt-1">Active this period</p>
          </CardContent>
        </Card>

        <Card className={`border-l-4 ${avgSatisfaction >= 4.5 ? 'border-l-green-500' : avgSatisfaction >= 4 ? 'border-l-amber-500' : 'border-l-red-500'}`}>
          <CardContent className="pt-4 pb-3">
            <p className="text-xs text-slate-500 uppercase tracking-wider">Satisfaction</p>
            <div className="flex items-center gap-2">
              <p className="text-2xl font-bold text-slate-900">{avgSatisfaction}</p>
              <div className="flex gap-0.5">
                {[...Array(5)].map((_, i) => (
                  <Star key={i} className={`w-3 h-3 ${i < Math.floor(avgSatisfaction) ? 'fill-amber-400 text-amber-400' : 'text-slate-300'}`} />
                ))}
              </div>
            </div>
            <p className={`text-xs mt-1 ${avgSatisfaction >= 4.5 ? 'text-green-600' : 'text-amber-600'}`}>
              {avgSatisfaction >= 4.5 ? '✓ Excellent' : 'Room to improve'}
            </p>
          </CardContent>
        </Card>

        <Card className={`border-l-4 ${parseFloat(repeatRate) >= 40 ? 'border-l-green-500' : 'border-l-amber-500'}`}>
          <CardContent className="pt-4 pb-3">
            <p className="text-xs text-slate-500 uppercase tracking-wider">Repeat Rate</p>
            <p className="text-2xl font-bold text-slate-900">{repeatRate}%</p>
            <p className="text-xs text-slate-500 mt-1">${(topClients.reduce((s, c) => s + c.revenue, 0) * 0.4).toLocaleString()} from repeats</p>
          </CardContent>
        </Card>

        <Card className="border-l-4 border-l-purple-500 bg-purple-50">
          <CardContent className="pt-4 pb-3">
            <p className="text-xs text-purple-600 uppercase tracking-wider font-semibold">Quick Decision</p>
            <p className="text-sm font-medium text-purple-900 mt-1">
              {lowEngagementClients.length > 2 
                ? `Re-engage ${lowEngagementClients.length} low-activity clients with special offers`
                : parseFloat(repeatRate) < 40
                ? 'Launch loyalty program to boost repeat bookings by 25%'
                : 'Top 3 clients ready for annual contract — lock in 12-month deals'
              }
            </p>
          </CardContent>
        </Card>
      </div>

      {/* Monthly Booking Trend */}
      <Card>
        <CardHeader>
          <CardTitle>Booking Trend Over Time</CardTitle>
        </CardHeader>
        <CardContent>
          <ResponsiveContainer width="100%" height={300}>
            <LineChart data={monthlyBookings}>
              <CartesianGrid strokeDasharray="3 3" />
              <XAxis dataKey="month" />
              <YAxis />
              <Tooltip />
              <Legend />
              <Line type="monotone" dataKey="bookings" stroke="#0A39DF" strokeWidth={2} name="Bookings" />
            </LineChart>
          </ResponsiveContainer>
        </CardContent>
      </Card>

      {/* Top Clients */}
      <Card>
        <CardHeader>
          <CardTitle>Top Clients by Bookings</CardTitle>
        </CardHeader>
        <CardContent>
          <ResponsiveContainer width="100%" height={400}>
            <BarChart data={topClients} layout="vertical">
              <CartesianGrid strokeDasharray="3 3" />
              <XAxis type="number" />
              <YAxis dataKey="name" type="category" width={150} />
              <Tooltip />
              <Legend />
              <Bar dataKey="bookings" fill="#0A39DF" name="Bookings" />
            </BarChart>
          </ResponsiveContainer>
        </CardContent>
      </Card>

      {/* Client List */}
      <Card>
        <CardHeader>
          <CardTitle>Client Details</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-3">
            {topClients.map((client, idx) => (
              <div key={idx} className="flex items-center justify-between p-3 bg-slate-50 rounded-lg">
                <div>
                  <p className="font-semibold text-slate-900">{client.name}</p>
                  <p className="text-sm text-slate-500">{client.bookings} bookings</p>
                </div>
                <Badge variant="outline" className="font-semibold">
                  ${client.revenue.toLocaleString()}
                </Badge>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>
    </div>
  );
}