'use client';

import { useState } from 'react';
import { Download, Search, FileJson } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';

interface ExportJob {
  id: string;
  userId: string;
  email?: string;
  status: string;
  format: string;
  requestedAt: string;
  completedAt?: string;
  downloadUrl?: string;
}

function formatDate(iso: string) {
  return new Date(iso).toLocaleString('en-US', {
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  });
}

export default function GdprExportPage() {
  const [jobs, setJobs] = useState<ExportJob[]>([]);
  const [loading, setLoading] = useState(false);
  const [userId, setUserId] = useState('');
  const [exporting, setExporting] = useState(false);
  const [exportResult, setExportResult] = useState<string | null>(null);

  async function handleLookup() {
    if (!userId.trim()) return;
    setLoading(true);
    try {
      const res = await fetch(`/api/exports?userId=${encodeURIComponent(userId)}`, {
        headers: { 'Content-Type': 'application/json' },
      });
      const data = await res.json();
      setJobs(Array.isArray(data?.exports) ? data.exports : Array.isArray(data) ? data : []);
    } catch {
      setJobs([]);
    }
    setLoading(false);
  }

  async function handleExport() {
    if (!userId.trim()) return;
    setExporting(true);
    setExportResult(null);
    try {
      const res = await fetch('/api/exports', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ userId: userId.trim(), entityTypes: ['all'], format: 'json' }),
      });
      const data = await res.json();
      if (res.ok) {
        setExportResult('Export job queued successfully.');
        handleLookup();
      } else {
        setExportResult(data.error || 'Failed to queue export.');
      }
    } catch {
      setExportResult('Error requesting export.');
    }
    setExporting(false);
  }

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold">GDPR Data Export</h1>
        <p className="text-sm text-muted-foreground">
          Export all user data for GDPR compliance (right of access / portability)
        </p>
      </div>

      <Card>
        <CardHeader>
          <CardTitle className="text-base">Request User Data Export</CardTitle>
          <CardDescription>
            Enter a user ID or email to export all their data as JSON.
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="flex items-end gap-3">
            <div className="flex-1 space-y-2">
              <Label>User ID or Email</Label>
              <Input
                placeholder="user-id or user@example.com"
                value={userId}
                onChange={e => setUserId(e.target.value)}
              />
            </div>
            <Button variant="outline" onClick={handleLookup} disabled={loading || !userId.trim()}>
              <Search className="mr-2 h-4 w-4" /> Lookup
            </Button>
            <Button onClick={handleExport} disabled={exporting || !userId.trim()}>
              <Download className="mr-2 h-4 w-4" /> {exporting ? 'Exporting...' : 'Export Data'}
            </Button>
          </div>
          {exportResult && (
            <p
              className={`text-sm ${exportResult.includes('success') ? 'text-emerald-600' : 'text-destructive'}`}
            >
              {exportResult}
            </p>
          )}
        </CardContent>
      </Card>

      {jobs.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle className="text-base">Export History</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-3">
              {jobs.map(job => (
                <div
                  key={job.id}
                  className="flex items-center justify-between rounded-lg border p-3"
                >
                  <div className="flex items-center gap-3">
                    <FileJson className="h-5 w-5 text-muted-foreground" />
                    <div>
                      <p className="text-sm font-medium">{job.email || job.userId}</p>
                      <p className="text-xs text-muted-foreground">
                        Requested {formatDate(job.requestedAt)}
                      </p>
                    </div>
                  </div>
                  <div className="flex items-center gap-2">
                    <Badge
                      className={
                        job.status === 'completed'
                          ? 'bg-emerald-50 text-emerald-700 border-0'
                          : job.status === 'pending'
                            ? 'bg-amber-50 text-amber-700 border-0'
                            : 'bg-gray-50 text-gray-600 border-0'
                      }
                    >
                      {job.status}
                    </Badge>
                    {job.status === 'completed' && job.downloadUrl && (
                      <Button variant="outline" size="sm" asChild>
                        <a href={job.downloadUrl} download>
                          <Download className="mr-1 h-3 w-3" /> Download
                        </a>
                      </Button>
                    )}
                  </div>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      )}

      {!loading && jobs.length === 0 && userId && (
        <Card>
          <CardContent className="py-8 text-center text-muted-foreground">
            <Download className="mx-auto mb-2 h-8 w-8 opacity-40" />
            No previous exports for this user.
          </CardContent>
        </Card>
      )}
    </div>
  );
}
