/**
 * ExportHistory component - View and manage past exports.
 *
 * Implements US8: Export History Management.
 *
 * @package GetMD
 * @since   1.0.0
 */

import { useState, useEffect } from 'react';
import { format } from 'date-fns';
import { Download, Trash2, RefreshCw } from 'lucide-react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from './ui/card';
import { Button } from './ui/button';
import { Badge } from './ui/badge';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from './ui/table';
import { getAPI } from '../lib/api';
import type { ExportJob } from '../types/wordpress';

/**
 * Displays a table of past export jobs and provides controls to refresh, download, and delete them.
 *
 * Loads export history on mount, shows loading and error states, and formats dates and file sizes. UI strings are sourced from window.summixGetmdData?.i18n with sensible fallbacks.
 *
 * @returns The Export History UI as a React element.
 */
export function ExportHistory() {
  const { i18n } = window.summixGetmdData || {};
  const [exports, setExports] = useState<ExportJob[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const loadHistory = async () => {
    setLoading(true);
    setError(null);
    try {
      const history = await getAPI().getExportHistory();
      setExports(history);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load history');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadHistory();
  }, []);

  const handleDelete = async (exportId: number) => {
    if (!confirm(i18n?.confirmDeleteExport || "Delete this export? This can't be undone.")) {
      return;
    }

    try {
      await getAPI().deleteExport(exportId);
      setExports(exports.filter((exp) => exp.export_id !== exportId));
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to delete export');
    }
  };

  const formatFileSize = (bytes: number): string => {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  const getStatusVariant = (status: string): 'success' | 'destructive' | 'warning' | 'secondary' => {
    switch (status) {
      case 'completed':
        return 'success';
      case 'failed':
        return 'destructive';
      case 'pending':
      case 'processing':
        return 'warning';
      default:
        return 'secondary';
    }
  };

  if (loading) {
    return (
      <Card>
        <CardContent className="smx-pt-6">
          <div className="smx-flex smx-items-center smx-justify-center smx-py-8">
            <RefreshCw className="smx-h-6 smx-w-6 smx-animate-spin" />
            <span className="smx-ml-2">{i18n?.loading || 'Loading...'}</span>
          </div>
        </CardContent>
      </Card>
    );
  }

  if (error) {
    return (
      <Card className="smx-border-destructive">
        <CardContent className="smx-pt-6">
          <p className="smx-text-destructive smx-text-sm">{error}</p>
        </CardContent>
      </Card>
    );
  }

  return (
    <Card>
      <CardHeader>
        <div className="smx-flex smx-items-center smx-justify-between">
          <div>
            <CardTitle>{i18n?.historyTitle || 'Export History'}</CardTitle>
            <CardDescription>
              {i18n?.historyDesc || 'Your recent exports are here.'}
            </CardDescription>
          </div>
          <Button
            variant="outline"
            size="sm"
            onClick={loadHistory}
            disabled={loading}
          >
            <RefreshCw className="smx-h-4 smx-w-4 smx-mr-2" />
            {i18n?.refresh || 'Refresh'}
          </Button>
        </div>
      </CardHeader>
      <CardContent>
        {exports.length === 0 ? (
          <div className="smx-text-center smx-py-8 smx-text-muted-foreground">
            {i18n?.noExportsYet || 'No exports yet'}
          </div>
        ) : (
          <div className="smx-rounded-md smx-border">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>{i18n?.created || 'Created'}</TableHead>
                  <TableHead>{i18n?.status || 'Status'}</TableHead>
                  <TableHead>{i18n?.files || 'Files'}</TableHead>
                  <TableHead>{i18n?.size || 'Size'}</TableHead>
                  <TableHead className="smx-text-right smx-sr-only">
                    {i18n?.actions || 'Actions'}
                  </TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {exports.map((exportJob) => (
                  <TableRow key={exportJob.export_id}>
                    <TableCell className="smx-font-medium">
                      {format(new Date(exportJob.created_at), 'MMM d, yyyy h:mm a')}
                    </TableCell>
                    <TableCell>
                      <Badge variant={getStatusVariant(exportJob.status)}>
                        {exportJob.status === 'processing' ? (i18n?.statusExporting || 'Exporting...')
                          : exportJob.status === 'completed' ? (i18n?.statusDone || 'Done')
                          : exportJob.status === 'failed' ? (i18n?.statusFailed || 'Failed')
                          : (i18n?.statusQueued || 'Queued')}
                      </Badge>
                    </TableCell>
                    <TableCell>{exportJob.file_count}</TableCell>
                    <TableCell>{formatFileSize(exportJob.file_size)}</TableCell>
                    <TableCell className="smx-text-right">
                      <div className="smx-flex smx-items-center smx-justify-end smx-gap-2">
                        {exportJob.status === 'completed' && exportJob.download_url && (
                          <Button
                            variant="ghost"
                            size="sm"
                            asChild
                          >
                            <a
                              href={exportJob.download_url}
                              title={i18n?.download || 'Download'}
                            >
                              <Download className="smx-h-4 smx-w-4" />
                            </a>
                          </Button>
                        )}
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => handleDelete(exportJob.export_id)}
                          title={i18n?.delete || 'Delete'}
                        >
                          <Trash2 className="smx-h-4 smx-w-4" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>
        )}
      </CardContent>
    </Card>
  );
}