import React, { useState, useEffect } from 'react';
import * as XLSX from 'xlsx';
import { getCategoryColor, getCategoryName } from '../data/kpiData';
import { useSQLiteDatabase } from '../database/useSQLiteDatabase';
import { ChartModal } from '../components/ChartModal';
import { ExportModal } from '../components/ExportModal';
import { RangeChartModal } from '../components/RangeChartModal';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '../components/ui/card';
import { Button } from '../components/ui/button';
import { Badge } from '../components/ui/badge';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../components/ui/table';
import { Download, LineChart } from 'lucide-react';

interface DetailPageProps {
  category: 'security' | 'quality' | 'delays' | 'costs' | 'maintenance';
}

const categoryMap: Record<string, number> = {
  security: 1,
  quality: 2,
  delays: 3,
  costs: 4,
  maintenance: 5
};

export const DetailPage: React.FC<DetailPageProps> = ({ category }) => {
  const db = useSQLiteDatabase();
  const categoryId = categoryMap[category];
  const [selectedKPIId, setSelectedKPIId] = useState<number | null>(null);
  const [selectedKPIMeasurements, setSelectedKPIMeasurements] = useState<any[]>([]);
  const [selectedKPIStats, setSelectedKPIStats] = useState<any>(null);
  const [showChart, setShowChart] = useState(false);
  const [showExportModal, setShowExportModal] = useState(false);
  const [showChartRangeModal, setShowChartRangeModal] = useState(false);

  const categoryKPIs = db.kpis.filter(kpi => kpi.category_id === categoryId);

  useEffect(() => {
    if (!selectedKPIId) {
      if (categoryKPIs.length > 0) {
        setSelectedKPIId(categoryKPIs[0].id);
      }
      return;
    }

    const fetchMeasurements = async () => {
      const measurements = await db.getMeasurementsForKPI(selectedKPIId, 365);
      const stats = await db.getKPIStats(selectedKPIId, 30);
      setSelectedKPIMeasurements(measurements || []);
      setSelectedKPIStats(stats);
    };

    fetchMeasurements();
  }, [selectedKPIId, categoryKPIs, db]);

  const selectedKPI = categoryKPIs.find(k => k.id === selectedKPIId);

  const exportToExcel = (kpi: any, measurements: any[]) => {
    if (!kpi || measurements.length === 0) return;

    const data = measurements.map(m => ({
      Date: new Date(m.measurement_date).toLocaleString('fr-FR'),
      Valeur: m.value,
      Statut: m.status,
    }));

    const worksheet = XLSX.utils.json_to_sheet(data);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, 'Mesures');

    const summary = [
      ['KPI', kpi.name],
      ['Unité', kpi.unit],
      ['Cible', kpi.target],
      ['Fréquence', kpi.frequency],
      ['Nombre de mesures', measurements.length],
      ['Date d\'export', new Date().toLocaleString('fr-FR')],
    ];

    const summarySheet = XLSX.utils.aoa_to_sheet(summary);
    XLSX.utils.book_append_sheet(workbook, summarySheet, 'Résumé');

    const filename = `${kpi.name.replace(/\s+/g, '_')}_${new Date().toISOString().split('T')[0]}.xlsx`;
    XLSX.writeFile(workbook, filename);
  };

  const handleExportClick = (days: number) => {
    if (!selectedKPI) return;

    let measurementsToExport = selectedKPIMeasurements;

    if (days > 0 && days !== 365) {
      measurementsToExport = selectedKPIMeasurements.filter((m: any) => {
        const daysAgo = (Date.now() - new Date(m.measurement_date).getTime()) / (1000 * 60 * 60 * 24);
        return daysAgo <= days;
      });
    }

    exportToExcel(selectedKPI, measurementsToExport);
  };

  const getMeasurementsForDateRange = (days: number) => {
    if (days === -1) return selectedKPIMeasurements;

    return selectedKPIMeasurements.filter((m: any) => {
      const daysAgo = (Date.now() - new Date(m.measurement_date).getTime()) / (1000 * 60 * 60 * 24);
      return daysAgo <= days;
    });
  };

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'good':
        return <Badge variant="success">On Target</Badge>;
      case 'warning':
        return <Badge variant="warning">Warning</Badge>;
      case 'critical':
        return <Badge variant="destructive">Critical</Badge>;
      default:
        return <Badge variant="outline">N/A</Badge>;
    }
  };

  return (
    <div className="container mx-auto p-6 space-y-6">
      {/* Header */}
      <div className="pb-4 border-b-2" style={{ borderColor: getCategoryColor(category) }}>
        <h1 className="text-4xl font-bold tracking-tight mb-2" style={{ color: getCategoryColor(category) }}>
          {getCategoryName(category)}
        </h1>
        <p className="text-lg text-muted-foreground">Detailed metric analysis and performance tracking</p>
      </div>

      <div className="grid gap-6 lg:grid-cols-3">
        {/* KPI Selector */}
        <Card className="lg:col-span-1">
          <CardHeader>
            <CardTitle>Sélectionner un KPI</CardTitle>
            <CardDescription>Choisissez un indicateur pour voir les détails</CardDescription>
          </CardHeader>
          <CardContent className="space-y-3">
            <div className="flex gap-2">
              <Button
                className="flex-1"
                size="sm"
                onClick={() => setShowExportModal(true)}
                disabled={!selectedKPI}
              >
                <Download className="h-4 w-4 mr-2" />
                Exporter
              </Button>
              <Button
                className="flex-1"
                size="sm"
                variant="outline"
                onClick={() => setShowChartRangeModal(true)}
                disabled={!selectedKPI}
              >
                <LineChart className="h-4 w-4 mr-2" />
                Graphique
              </Button>
            </div>

            <div className="space-y-2">
              {categoryKPIs.map(kpi => (
                <button
                  key={kpi.id}
                  className={`w-full text-left p-3 rounded-lg border transition-colors ${
                    selectedKPIId === kpi.id
                      ? 'border-primary bg-primary/10'
                      : 'border-border hover:bg-accent'
                  }`}
                  onClick={() => setSelectedKPIId(kpi.id)}
                >
                  <div className="font-medium text-sm">{kpi.name}</div>
                  <div className="text-xs text-muted-foreground">{kpi.unit}</div>
                </button>
              ))}
            </div>
          </CardContent>
        </Card>

        {/* KPI Details */}
        {selectedKPI && (
          <div className="lg:col-span-2 space-y-6">
            {/* KPI Info */}
            <Card>
              <CardHeader>
                <CardTitle>{selectedKPI.name}</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="grid grid-cols-3 gap-4">
                  <div>
                    <div className="text-sm text-muted-foreground">Unité</div>
                    <div className="font-medium">{selectedKPI.unit}</div>
                  </div>
                  <div>
                    <div className="text-sm text-muted-foreground">Cible</div>
                    <div className="font-medium">{selectedKPI.target}</div>
                  </div>
                  <div>
                    <div className="text-sm text-muted-foreground">Fréquence</div>
                    <div className="font-medium">{selectedKPI.frequency || 'N/A'}</div>
                  </div>
                </div>

                <div>
                  <h4 className="font-semibold mb-2">Description</h4>
                  <p className="text-sm text-muted-foreground">{selectedKPI.description}</p>
                </div>

                <div>
                  <h4 className="font-semibold mb-2">Formule</h4>
                  <p className="text-sm text-muted-foreground">{selectedKPI.formula}</p>
                </div>
              </CardContent>
            </Card>

            {/* Statistics */}
            {selectedKPIStats && (
              <Card>
                <CardHeader>
                  <CardTitle>Statistiques (30 derniers jours)</CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="grid grid-cols-4 gap-4">
                    <div className="text-center">
                      <div className="text-2xl font-bold">{selectedKPIStats.avg?.toFixed(2) || 'N/A'}</div>
                      <div className="text-sm text-muted-foreground">Moyenne</div>
                    </div>
                    <div className="text-center">
                      <div className="text-2xl font-bold">{selectedKPIStats.min?.toFixed(2) || 'N/A'}</div>
                      <div className="text-sm text-muted-foreground">Min</div>
                    </div>
                    <div className="text-center">
                      <div className="text-2xl font-bold">{selectedKPIStats.max?.toFixed(2) || 'N/A'}</div>
                      <div className="text-sm text-muted-foreground">Max</div>
                    </div>
                    <div className="text-center">
                      <div className="text-2xl font-bold">{selectedKPIStats.count || 0}</div>
                      <div className="text-sm text-muted-foreground">Mesures</div>
                    </div>
                  </div>
                </CardContent>
              </Card>
            )}

            {/* Measurements Table */}
            <Card>
              <CardHeader>
                <CardTitle>Dernières mesures ({selectedKPIMeasurements.length})</CardTitle>
              </CardHeader>
              <CardContent>
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Date</TableHead>
                      <TableHead>Valeur</TableHead>
                      <TableHead>Statut</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {selectedKPIMeasurements.slice(-10).reverse().map((m: any, idx: number) => (
                      <TableRow key={idx}>
                        <TableCell>{new Date(m.measurement_date).toLocaleString('fr-FR')}</TableCell>
                        <TableCell>{m.value}</TableCell>
                        <TableCell>{getStatusBadge(m.status)}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </CardContent>
            </Card>
          </div>
        )}
      </div>

      <ChartModal
        isOpen={showChart}
        kpi={selectedKPI}
        measurements={selectedKPIMeasurements}
        onClose={() => setShowChart(false)}
      />

      <ExportModal
        isOpen={showExportModal}
        kpiName={selectedKPI?.name || ''}
        onExport={handleExportClick}
        onClose={() => setShowExportModal(false)}
      />

      <RangeChartModal
        isOpen={showChartRangeModal}
        kpi={selectedKPI}
        measurements={selectedKPIMeasurements}
        getMeasurementsForRange={getMeasurementsForDateRange}
        onClose={() => setShowChartRangeModal(false)}
      />
    </div>
  );
};
