import { useCoverageStore } from '@/store/coverage.ts';
import { useToastStore } from '@/components/ui/Toast.tsx';
import Button from '@/components/ui/Button.tsx';

export default function ExportPanel() {
  const result = useCoverageStore((s) => s.result);
  const addToast = useToastStore((s) => s.addToast);

  const points = result?.points ?? [];

  const downloadBlob = (blob: Blob, filename: string) => {
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  };

  const exportCSV = () => {
    if (points.length === 0) {
      addToast('No coverage data to export. Run a calculation first.', 'error');
      return;
    }

    const csv = [
      'lat,lon,rsrp,site_id',
      ...points.map((p) => `${p.lat},${p.lon},${p.rsrp},${p.siteId}`),
    ].join('\n');

    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8' });
    downloadBlob(blob, `rfcp-coverage-${Date.now()}.csv`);
    addToast(`Exported ${points.length.toLocaleString()} points as CSV`, 'success');
  };

  const exportGeoJSON = () => {
    if (points.length === 0) {
      addToast('No coverage data to export. Run a calculation first.', 'error');
      return;
    }

    const geojson = {
      type: 'FeatureCollection' as const,
      features: points.map((p) => ({
        type: 'Feature' as const,
        geometry: {
          type: 'Point' as const,
          coordinates: [p.lon, p.lat],
        },
        properties: {
          rsrp: p.rsrp,
          siteId: p.siteId,
        },
      })),
    };

    const blob = new Blob([JSON.stringify(geojson, null, 2)], {
      type: 'application/geo+json;charset=utf-8',
    });
    downloadBlob(blob, `rfcp-coverage-${Date.now()}.geojson`);
    addToast(`Exported ${points.length.toLocaleString()} points as GeoJSON`, 'success');
  };

  return (
    <div className="bg-white dark:bg-dark-surface border border-gray-200 dark:border-dark-border rounded-lg shadow-sm p-4 space-y-3">
      <h3 className="text-sm font-semibold text-gray-800 dark:text-dark-text">
        Export Coverage
      </h3>
      {points.length > 0 ? (
        <>
          <p className="text-xs text-gray-500 dark:text-dark-muted">
            {points.length.toLocaleString()} coverage points available
          </p>
          <div className="flex gap-2">
            <Button onClick={exportCSV} size="sm" variant="secondary">
              CSV
            </Button>
            <Button onClick={exportGeoJSON} size="sm" variant="secondary">
              GeoJSON
            </Button>
          </div>
        </>
      ) : (
        <p className="text-xs text-gray-400 dark:text-dark-muted">
          No coverage data. Calculate coverage first to enable export.
        </p>
      )}
    </div>
  );
}
