'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { Loader2 } from 'lucide-react';
import { toast } from 'sonner';

import { Button } from '@/components/ui/button';
import { DatePicker } from '@/components/ui/date-picker';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Label } from '@/components/ui/label';
import { apiFetch } from '@/lib/api/client';

function toIsoLocal(d: Date): string {
  const y = d.getFullYear();
  const m = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  return `${y}-${m}-${day}`;
}

const KIND_LABELS: Record<string, { title: string; description: string }> = {
  clients: {
    title: 'Clients report',
    description: 'Activity snapshot for every active client in the window.',
  },
  berths: {
    title: 'Berths report',
    description: 'Occupancy + status mix for every berth in the window.',
  },
  interests: {
    title: 'Interests report',
    description: 'Pipeline value + stage distribution for every interest.',
  },
};

interface Props {
  portSlug: string;
  kind: 'clients' | 'berths' | 'interests';
}

/**
 * v1 builder for the non-dashboard kinds. Just a date-range picker that
 * enqueues a `report_runs` row via /api/v1/reports/runs. Kind-specific
 * filters land alongside the dedicated renderer in P6+.
 */
export function SimpleReportBuilder({ portSlug, kind }: Props) {
  const router = useRouter();
  const labels = KIND_LABELS[kind] ?? {
    title: `${kind} report`,
    description: 'Generate a port-scoped report.',
  };

  const today = new Date();
  const last30 = new Date(today);
  last30.setDate(last30.getDate() - 30);
  const [dateFrom, setDateFrom] = useState(toIsoLocal(last30));
  const [dateTo, setDateTo] = useState(toIsoLocal(today));
  const [outputFormat, setOutputFormat] = useState<'pdf' | 'csv'>('pdf');
  const [enqueuing, setEnqueuing] = useState(false);

  async function handleEnqueue() {
    setEnqueuing(true);
    try {
      await apiFetch('/api/v1/reports/runs', {
        method: 'POST',
        body: {
          kind,
          config: { kind, dateFrom, dateTo },
          outputFormat,
        },
      });
      toast.success('Report queued — track progress in Runs.');
      router.push(`/${portSlug}/reports/runs`);
    } catch (err) {
      toast.error(err instanceof Error ? err.message : 'Enqueue failed');
    } finally {
      setEnqueuing(false);
    }
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle className="text-sm">{labels.title}</CardTitle>
      </CardHeader>
      <CardContent className="space-y-4">
        <p className="text-xs text-muted-foreground">{labels.description}</p>
        <div className="space-y-1">
          <Label>Report window</Label>
          <div className="flex flex-wrap items-center gap-2">
            <DatePicker
              id="builder-date-from"
              value={dateFrom}
              onChange={setDateFrom}
              placeholder="Start"
              size="sm"
              className="w-[150px]"
            />
            <span className="text-xs text-muted-foreground">→</span>
            <DatePicker
              id="builder-date-to"
              value={dateTo}
              onChange={setDateTo}
              placeholder="End"
              size="sm"
              className="w-[150px]"
            />
          </div>
        </div>
        <div className="space-y-1">
          <Label>Output format</Label>
          <div className="flex gap-2">
            {(['pdf', 'csv'] as const).map((f) => (
              <Button
                key={f}
                type="button"
                size="sm"
                variant={outputFormat === f ? 'default' : 'outline'}
                onClick={() => setOutputFormat(f)}
              >
                {f.toUpperCase()}
              </Button>
            ))}
          </div>
          <p className="text-xs text-muted-foreground">
            PDF for printable / branded reports; CSV for spreadsheet analysis.
          </p>
        </div>
        <div className="flex justify-end">
          <Button onClick={handleEnqueue} disabled={enqueuing}>
            {enqueuing ? <Loader2 className="mr-1.5 h-4 w-4 animate-spin" aria-hidden /> : null}
            Queue + go to Runs
          </Button>
        </div>
      </CardContent>
    </Card>
  );
}
