import React from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Download, TrendingUp, Users, Star } 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";

export default function ClientTrendsReport({ events, invoices }) {
  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" });
  };

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <div>
          <h2 className="text-xl font-bold text-slate-900">Client Satisfaction & Booking Trends</h2>
          <p className="text-sm text-slate-500">Track client engagement and satisfaction metrics</p>
        </div>
        <Button onClick={handleExport} variant="outline">
          <Download className="w-4 h-4 mr-2" />
          Export CSV
        </Button>
      </div>

      {/* Summary Cards */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <Card>
          <CardContent className="pt-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-slate-500">Total Clients</p>
                <p className="text-2xl font-bold text-slate-900">{totalClients}</p>
              </div>
              <div className="w-12 h-12 bg-blue-100 rounded-full flex items-center justify-center">
                <Users className="w-6 h-6 text-blue-600" />
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="pt-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-slate-500">Avg Satisfaction</p>
                <p className="text-2xl font-bold text-slate-900">{avgSatisfaction}/5</p>
                <div className="flex gap-0.5 mt-1">
                  {[...Array(5)].map((_, i) => (
                    <Star key={i} className={`w-4 h-4 ${i < Math.floor(avgSatisfaction) ? 'fill-amber-400 text-amber-400' : 'text-slate-300'}`} />
                  ))}
                </div>
              </div>
              <div className="w-12 h-12 bg-amber-100 rounded-full flex items-center justify-center">
                <Star className="w-6 h-6 text-amber-600" />
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="pt-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-slate-500">Repeat Rate</p>
                <p className="text-2xl font-bold text-slate-900">{repeatRate}%</p>
              </div>
              <div className="w-12 h-12 bg-green-100 rounded-full flex items-center justify-center">
                <TrendingUp className="w-6 h-6 text-green-600" />
              </div>
            </div>
          </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>
  );
}