import React, { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Download, Plus, X } from "lucide-react";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Checkbox } from "@/components/ui/checkbox";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { useToast } from "@/components/ui/use-toast";

export default function CustomReportBuilder({ events, staff, invoices }) {
  const { toast } = useToast();
  const [reportConfig, setReportConfig] = useState({
    name: "",
    dataSource: "events",
    dateRange: "30",
    fields: [],
    filters: [],
    groupBy: "",
  });

  const dataSourceFields = {
    events: ['event_name', 'business_name', 'status', 'date', 'total', 'requested', 'hub'],
    staff: ['employee_name', 'position', 'department', 'hub_location', 'rating', 'reliability_score'],
    invoices: ['invoice_number', 'business_name', 'amount', 'status', 'issue_date', 'due_date'],
  };

  const handleFieldToggle = (field) => {
    setReportConfig(prev => ({
      ...prev,
      fields: prev.fields.includes(field)
        ? prev.fields.filter(f => f !== field)
        : [...prev.fields, field],
    }));
  };

  const handleGenerateReport = () => {
    if (!reportConfig.name || reportConfig.fields.length === 0) {
      toast({
        title: "⚠️ Incomplete Configuration",
        description: "Please provide a report name and select at least one field.",
        variant: "destructive",
      });
      return;
    }

    // Get data based on source
    let data = [];
    if (reportConfig.dataSource === 'events') data = events;
    else if (reportConfig.dataSource === 'staff') data = staff;
    else if (reportConfig.dataSource === 'invoices') data = invoices;

    // Filter data by selected fields
    const filteredData = data.map(item => {
      const filtered = {};
      reportConfig.fields.forEach(field => {
        filtered[field] = item[field] || '-';
      });
      return filtered;
    });

    // Generate CSV
    const headers = reportConfig.fields.join(',');
    const rows = filteredData.map(item => 
      reportConfig.fields.map(field => `"${item[field]}"`).join(',')
    );
    const csv = [headers, ...rows].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 = `${reportConfig.name.replace(/\s+/g, '-').toLowerCase()}-${new Date().toISOString().split('T')[0]}.csv`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);

    toast({
      title: "✅ Report Generated",
      description: `${reportConfig.name} has been exported successfully.`,
    });
  };

  const handleExportJSON = () => {
    if (!reportConfig.name || reportConfig.fields.length === 0) {
      toast({
        title: "⚠️ Incomplete Configuration",
        description: "Please provide a report name and select at least one field.",
        variant: "destructive",
      });
      return;
    }

    let data = [];
    if (reportConfig.dataSource === 'events') data = events;
    else if (reportConfig.dataSource === 'staff') data = staff;
    else if (reportConfig.dataSource === 'invoices') data = invoices;

    const filteredData = data.map(item => {
      const filtered = {};
      reportConfig.fields.forEach(field => {
        filtered[field] = item[field] || null;
      });
      return filtered;
    });

    const jsonData = {
      reportName: reportConfig.name,
      generatedAt: new Date().toISOString(),
      dataSource: reportConfig.dataSource,
      recordCount: filteredData.length,
      data: filteredData,
    };

    const blob = new Blob([JSON.stringify(jsonData, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `${reportConfig.name.replace(/\s+/g, '-').toLowerCase()}-${new Date().toISOString().split('T')[0]}.json`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);

    toast({
      title: "✅ JSON Exported",
      description: `${reportConfig.name} exported as JSON.`,
    });
  };

  const availableFields = dataSourceFields[reportConfig.dataSource] || [];

  return (
    <div className="space-y-6">
      <div>
        <h2 className="text-xl font-bold text-slate-900">Custom Report Builder</h2>
        <p className="text-sm text-slate-500">Create custom reports with selected fields and filters</p>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        {/* Configuration Panel */}
        <Card>
          <CardHeader>
            <CardTitle>Report Configuration</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div>
              <Label>Report Name</Label>
              <Input
                value={reportConfig.name}
                onChange={(e) => setReportConfig(prev => ({ ...prev, name: e.target.value }))}
                placeholder="e.g., Monthly Performance Report"
              />
            </div>

            <div>
              <Label>Data Source</Label>
              <Select
                value={reportConfig.dataSource}
                onValueChange={(value) => setReportConfig(prev => ({ ...prev, dataSource: value, fields: [] }))}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="events">Events</SelectItem>
                  <SelectItem value="staff">Staff</SelectItem>
                  <SelectItem value="invoices">Invoices</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div>
              <Label>Date Range</Label>
              <Select
                value={reportConfig.dateRange}
                onValueChange={(value) => setReportConfig(prev => ({ ...prev, dateRange: value }))}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="7">Last 7 days</SelectItem>
                  <SelectItem value="30">Last 30 days</SelectItem>
                  <SelectItem value="90">Last 90 days</SelectItem>
                  <SelectItem value="365">Last year</SelectItem>
                  <SelectItem value="all">All time</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div>
              <Label className="mb-3 block">Select Fields to Include</Label>
              <div className="space-y-2 max-h-60 overflow-y-auto border border-slate-200 rounded-lg p-3">
                {availableFields.map(field => (
                  <div key={field} className="flex items-center gap-2">
                    <Checkbox
                      id={field}
                      checked={reportConfig.fields.includes(field)}
                      onCheckedChange={() => handleFieldToggle(field)}
                    />
                    <Label htmlFor={field} className="cursor-pointer text-sm">
                      {field.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase())}
                    </Label>
                  </div>
                ))}
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Preview Panel */}
        <Card>
          <CardHeader>
            <CardTitle>Report Preview</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            {reportConfig.name && (
              <div>
                <Label className="text-xs text-slate-500">Report Name</Label>
                <p className="font-semibold text-slate-900">{reportConfig.name}</p>
              </div>
            )}

            <div>
              <Label className="text-xs text-slate-500">Data Source</Label>
              <Badge variant="outline" className="mt-1">
                {reportConfig.dataSource.charAt(0).toUpperCase() + reportConfig.dataSource.slice(1)}
              </Badge>
            </div>

            {reportConfig.fields.length > 0 && (
              <div>
                <Label className="text-xs text-slate-500 mb-2 block">Selected Fields ({reportConfig.fields.length})</Label>
                <div className="flex flex-wrap gap-2">
                  {reportConfig.fields.map(field => (
                    <Badge key={field} className="bg-blue-100 text-blue-700">
                      {field.replace(/_/g, ' ')}
                      <button
                        onClick={() => handleFieldToggle(field)}
                        className="ml-1 hover:text-blue-900"
                      >
                        <X className="w-3 h-3" />
                      </button>
                    </Badge>
                  ))}
                </div>
              </div>
            )}

            <div className="pt-4 border-t space-y-2">
              <Button
                onClick={handleGenerateReport}
                className="w-full bg-[#0A39DF]"
                disabled={!reportConfig.name || reportConfig.fields.length === 0}
              >
                <Download className="w-4 h-4 mr-2" />
                Export as CSV
              </Button>
              <Button
                onClick={handleExportJSON}
                variant="outline"
                className="w-full"
                disabled={!reportConfig.name || reportConfig.fields.length === 0}
              >
                <Download className="w-4 h-4 mr-2" />
                Export as JSON
              </Button>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Saved Report Templates */}
      <Card>
        <CardHeader>
          <CardTitle>Quick Templates</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
            <Button
              variant="outline"
              className="justify-start"
              onClick={() => setReportConfig({
                name: "Staff Performance Summary",
                dataSource: "staff",
                dateRange: "30",
                fields: ['employee_name', 'position', 'rating', 'reliability_score'],
                filters: [],
                groupBy: "",
              })}
            >
              <Plus className="w-4 h-4 mr-2" />
              Staff Performance
            </Button>
            <Button
              variant="outline"
              className="justify-start"
              onClick={() => setReportConfig({
                name: "Event Cost Summary",
                dataSource: "events",
                dateRange: "90",
                fields: ['event_name', 'business_name', 'date', 'total', 'status'],
                filters: [],
                groupBy: "",
              })}
            >
              <Plus className="w-4 h-4 mr-2" />
              Event Costs
            </Button>
            <Button
              variant="outline"
              className="justify-start"
              onClick={() => setReportConfig({
                name: "Invoice Status Report",
                dataSource: "invoices",
                dateRange: "30",
                fields: ['invoice_number', 'business_name', 'amount', 'status', 'due_date'],
                filters: [],
                groupBy: "",
              })}
            >
              <Plus className="w-4 h-4 mr-2" />
              Invoice Status
            </Button>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}