import { useState } from 'react';
import { useParams, Link } from 'react-router-dom';
import { ArrowLeft, FileText, Download, Trash2, Loader2, RefreshCw } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Checkbox } from '@/components/ui/checkbox';
import { Label } from '@/components/ui/label';
import { 
  useReports, 
  useGenerateReport, 
  useDownloadReport, 
  useDeleteReport,
  formatFileSize,
  getStatusBadgeVariant,
  type ReportSection,
  type ReportFormat,
} from '@/hooks/useReports';
import { useScenario } from '@/hooks/useScenarios';
import { Skeleton } from '@/components/ui/skeleton';

const SECTIONS: { key: ReportSection; label: string }[] = [
  { key: 'summary', label: 'Summary' },
  { key: 'costs', label: 'Cost Breakdown' },
  { key: 'metrics', label: 'Metrics' },
  { key: 'logs', label: 'Logs' },
  { key: 'pii', label: 'PII Analysis' },
];

export function Reports() {
  const { id: scenarioId } = useParams<{ id: string }>();
  const [format, setFormat] = useState<ReportFormat>('pdf');
  const [selectedSections, setSelectedSections] = useState<ReportSection[]>(['summary', 'costs', 'metrics']);
  const [includeLogs, setIncludeLogs] = useState(false);

  const { data: scenario, isLoading: scenarioLoading } = useScenario(scenarioId || '');
  const { data: reports, isLoading: reportsLoading } = useReports(scenarioId || '');
  const generateReport = useGenerateReport(scenarioId || '');
  const downloadReport = useDownloadReport();
  const deleteReport = useDeleteReport(scenarioId || '');

  const toggleSection = (section: ReportSection) => {
    setSelectedSections((prev) =>
      prev.includes(section)
        ? prev.filter((s) => s !== section)
        : [...prev, section]
    );
  };

  const handleGenerate = () => {
    generateReport.mutate({
      format,
      sections: selectedSections,
      include_logs: includeLogs,
    });
  };

  const handleDownload = (reportId: string, fileName: string) => {
    downloadReport.mutate(
      { reportId, fileName },
      {
        onSuccess: (blob) => {
          const url = window.URL.createObjectURL(blob);
          const a = document.createElement('a');
          a.href = url;
          a.download = fileName;
          document.body.appendChild(a);
          a.click();
          window.URL.revokeObjectURL(url);
          document.body.removeChild(a);
        },
      }
    );
  };

  if (scenarioLoading || reportsLoading) {
    return (
      <div className="space-y-6">
        <Skeleton className="h-8 w-64" />
        <div className="grid gap-6 lg:grid-cols-2">
          <Skeleton className="h-[400px]" />
          <Skeleton className="h-[400px]" />
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center gap-4">
        <Link to={`/scenarios/${scenarioId}`}>
          <Button variant="ghost" size="icon">
            <ArrowLeft className="h-4 w-4" />
          </Button>
        </Link>
        <div>
          <h1 className="text-3xl font-bold">Reports</h1>
          <p className="text-muted-foreground">
            Generate and manage reports for {scenario?.name}
          </p>
        </div>
      </div>

      <div className="grid gap-6 lg:grid-cols-2">
        {/* Generate Report Form */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <FileText className="h-5 w-5" />
              Generate Report
            </CardTitle>
            <CardDescription>
              Create a new PDF or CSV report for this scenario
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-6">
            {/* Format Selection */}
            <div className="space-y-3">
              <Label>Format</Label>
              <div className="flex gap-2">
                <Button
                  type="button"
                  variant={format === 'pdf' ? 'default' : 'outline'}
                  onClick={() => setFormat('pdf')}
                  className="flex-1"
                >
                  PDF
                </Button>
                <Button
                  type="button"
                  variant={format === 'csv' ? 'default' : 'outline'}
                  onClick={() => setFormat('csv')}
                  className="flex-1"
                >
                  CSV
                </Button>
              </div>
            </div>

            {/* Sections */}
            <div className="space-y-3">
              <Label>Sections to Include</Label>
              <div className="grid grid-cols-2 gap-3">
                {SECTIONS.map((section) => (
                  <div key={section.key} className="flex items-center space-x-2">
                    <Checkbox
                      id={section.key}
                      checked={selectedSections.includes(section.key)}
                      onCheckedChange={() => toggleSection(section.key)}
                    />
                    <Label htmlFor={section.key} className="text-sm cursor-pointer">
                      {section.label}
                    </Label>
                  </div>
                ))}
              </div>
            </div>

            {/* Include Logs */}
            <div className="flex items-center space-x-2">
              <Checkbox
                id="include-logs"
                checked={includeLogs}
                onCheckedChange={(checked: boolean | 'indeterminate') => setIncludeLogs(checked === true)}
              />
              <Label htmlFor="include-logs" className="cursor-pointer">
                Include detailed logs (may increase file size)
              </Label>
            </div>

            {/* Preview Info */}
            <div className="rounded-lg bg-muted p-4 text-sm">
              <p className="font-medium mb-2">Report Preview</p>
              <ul className="space-y-1 text-muted-foreground">
                <li>• Format: {format.toUpperCase()}</li>
                <li>• Sections: {selectedSections.length} selected</li>
                <li>• Estimated size: {format === 'pdf' ? '~500 KB' : '~2 MB'}</li>
              </ul>
            </div>

            {/* Generate Button */}
            <Button
              onClick={handleGenerate}
              disabled={generateReport.isPending || selectedSections.length === 0}
              className="w-full"
            >
              {generateReport.isPending ? (
                <>
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  Generating...
                </>
              ) : (
                <>
                  <FileText className="mr-2 h-4 w-4" />
                  Generate Report
                </>
              )}
            </Button>
          </CardContent>
        </Card>

        {/* Reports List */}
        <Card>
          <CardHeader>
            <CardTitle>Generated Reports</CardTitle>
            <CardDescription>
              Download or manage existing reports
            </CardDescription>
          </CardHeader>
          <CardContent>
            {reports?.items.length === 0 ? (
              <div className="text-center py-8 text-muted-foreground">
                No reports generated yet
              </div>
            ) : (
              <div className="space-y-3">
                {reports?.items.map((report) => (
                  <div
                    key={report.id}
                    className="flex items-center justify-between p-3 rounded-lg border hover:bg-muted/50 transition-colors"
                  >
                    <div className="flex items-center gap-3">
                      <div className={`p-2 rounded-md ${
                        report.format === 'pdf' ? 'bg-red-100 text-red-600' : 'bg-green-100 text-green-600'
                      }`}>
                        <FileText className="h-4 w-4" />
                      </div>
                      <div>
                        <p className="font-medium text-sm">
                          {new Date(report.created_at).toLocaleString()}
                        </p>
                        <div className="flex items-center gap-2 text-xs text-muted-foreground">
                          <Badge variant={getStatusBadgeVariant(report.status)}>
                            {report.status}
                          </Badge>
                          <span>{formatFileSize(report.file_size)}</span>
                          <span className="uppercase">{report.format}</span>
                        </div>
                      </div>
                    </div>
                    <div className="flex items-center gap-1">
                      {report.status === 'completed' && (
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={() => handleDownload(
                            report.id,
                            `${scenario?.name}_${new Date(report.created_at).toISOString().split('T')[0]}.${report.format}`
                          )}
                          disabled={downloadReport.isPending}
                        >
                          <Download className="h-4 w-4" />
                        </Button>
                      )}
                      {report.status === 'failed' && (
                        <Button variant="ghost" size="icon">
                          <RefreshCw className="h-4 w-4" />
                        </Button>
                      )}
                      <Button
                        variant="ghost"
                        size="icon"
                        onClick={() => deleteReport.mutate(report.id)}
                        disabled={deleteReport.isPending}
                      >
                        <Trash2 className="h-4 w-4 text-destructive" />
                      </Button>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
