import {
  CheckCircle2,
  Download,
  ExternalLink,
  FileText,
  Loader2,
  Share2,
  Timer,
  Trash2,
} from 'lucide-react';

import { useState } from 'react';

import { Head, router, useForm, usePage } from '@inertiajs/react';

import SiteNav from '@/Components/Navigation/SiteNav';
import ReportPreview from '@/Components/Reports/ReportPreview';
import { Button } from '@/Components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/Components/ui/card';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/Components/ui/dialog';
import { EmptyState } from '@/Components/ui/empty-state';
import { Input } from '@/Components/ui/input';
import { Label } from '@/Components/ui/label';
import { LoadingButton } from '@/Components/ui/loading-button';
import { usePolling } from '@/hooks/usePolling';
import DashboardLayout from '@/Layouts/DashboardLayout';
import { formatDate } from '@/lib/format';
import { type PageProps, type SiteBasic } from '@/types';

interface Report {
  id: number;
  name: string;
  sections: string[];
  filters: Record<string, string>;
  status: string;
  generated_at: string | null;
  created_at: string;
  has_pdf: boolean;
  pdf_path: string | null;
  data: Record<string, unknown> | null;
}

interface SharedLink {
  id: number;
  token: string;
  expires_at: string | null;
  has_password: boolean;
  view_count: number;
  last_viewed_at: string | null;
  is_expired: boolean;
}

interface Props {
  site: SiteBasic;
  report: Report;
  sharedLinks: SharedLink[];
}

export default function Preview({ site, report, sharedLinks }: Props) {
  const { app_url, polling_interval_ms } = usePage<PageProps>().props;
  const [showShareDialog, setShowShareDialog] = useState(false);
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);

  // Poll when report is being generated
  usePolling(
    Boolean(report.status === 'pending' || report.status === 'processing'),
    polling_interval_ms ?? 3000,
    ['report'],
  );

  const { post: exportToPdf, processing: isExporting } = useForm({});
  const { delete: deleteReport, processing: isDeleting } = useForm({});

  const {
    data: shareData,
    setData: setShareData,
    post: submitShare,
    processing: isSharing,
    reset: resetShareForm,
  } = useForm({
    expires_at: '',
    password: '',
  });

  const handleExport = () => {
    exportToPdf(route('sites.reports.export', [site.id, report.id]));
  };

  const handleDownload = () => {
    window.location.href = route('sites.reports.download', [site.id, report.id]);
  };

  const handleShare = () => {
    submitShare(route('sites.reports.share', [site.id, report.id]), {
      onSuccess: () => {
        setShowShareDialog(false);
        resetShareForm();
      },
    });
  };

  const handleDelete = () => {
    deleteReport(route('sites.reports.destroy', [site.id, report.id]));
  };

  const copyShareLink = (token: string) => {
    const url = route('shared-reports.show', token);
    const fullUrl = `${app_url}${url}`;
    navigator.clipboard.writeText(fullUrl);
  };

  return (
    <DashboardLayout>
      <Head title={`${report.name} - Reports`} />

      <div className="space-y-6">
        <SiteNav siteId={site.id} />

        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-3xl font-bold tracking-tight">{report.name}</h1>
            <p className="mt-2 text-muted-foreground">
              {site.name} &middot; {site.domain}
            </p>
          </div>
          <div className="flex items-center gap-2">
            <Button
              variant="outline"
              onClick={() => router.visit(route('sites.reports.index', site.id))}
            >
              <FileText className="mr-2 h-4 w-4" />
              All Reports
            </Button>
            {report.status === 'completed' && !report.has_pdf && (
              <LoadingButton onClick={handleExport} loading={isExporting} variant="outline">
                <Download className="mr-2 h-4 w-4" />
                Export to PDF
              </LoadingButton>
            )}
            {report.has_pdf && (
              <Button variant="outline" onClick={handleDownload}>
                <Download className="mr-2 h-4 w-4" />
                Download PDF
              </Button>
            )}
            {report.status === 'completed' && (
              <Button variant="outline" onClick={() => setShowShareDialog(true)}>
                <Share2 className="mr-2 h-4 w-4" />
                Share
              </Button>
            )}
            <Button variant="destructive" onClick={() => setShowDeleteDialog(true)}>
              <Trash2 className="mr-2 h-4 w-4" />
              Delete
            </Button>
          </div>
        </div>

        {/* Status Card */}
        {report.status === 'pending' && (
          <Card className="border-warning/30 bg-warning/10">
            <CardHeader>
              <div className="flex items-center gap-3">
                <Timer className="h-6 w-6 text-warning" />
                <div>
                  <CardTitle className="text-warning">Report Queued</CardTitle>
                  <CardDescription className="text-warning/80">
                    Your report is waiting to be generated. This usually begins within a few
                    seconds.
                  </CardDescription>
                </div>
              </div>
            </CardHeader>
          </Card>
        )}

        {report.status === 'processing' && (
          <Card className="border-info/30 bg-info/10">
            <CardHeader>
              <div className="flex items-center gap-3">
                <Loader2 className="h-6 w-6 animate-spin text-info" />
                <div>
                  <CardTitle className="text-info">Generating Report...</CardTitle>
                  <CardDescription className="text-info/80">
                    This may take a few minutes depending on the amount of data. The page will
                    update automatically.
                  </CardDescription>
                </div>
              </div>
            </CardHeader>
          </Card>
        )}

        {report.status === 'failed' && (
          <Card className="border-destructive/30 bg-destructive/10">
            <CardHeader>
              <div>
                <CardTitle className="text-destructive">Report Generation Failed</CardTitle>
                <CardDescription className="text-destructive/80">
                  An error occurred while generating this report. Try creating a new report
                  or contact support if the issue persists.
                </CardDescription>
              </div>
            </CardHeader>
          </Card>
        )}

        {report.status === 'completed' && report.generated_at && (
          <Card className="border-success/30 bg-success/10">
            <CardHeader>
              <div className="flex items-center gap-3">
                <CheckCircle2 className="h-6 w-6 text-success" />
                <div>
                  <CardTitle className="text-success">Report Ready</CardTitle>
                  <CardDescription className="text-success/80">
                    Generated on {formatDate(report.generated_at)}
                  </CardDescription>
                </div>
              </div>
            </CardHeader>
          </Card>
        )}

        {/* Shared Links */}
        {sharedLinks.length > 0 && (
          <Card>
            <CardHeader>
              <CardTitle>Shared Links</CardTitle>
              <CardDescription>Manage shareable links for this report</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-3">
                {sharedLinks.map((link) => (
                  <div
                    key={link.id}
                    className="flex items-center justify-between rounded-lg border p-3"
                  >
                    <div className="flex-1">
                      <p className="text-sm font-medium">
                        {link.is_expired ? (
                          <span className="text-muted-foreground">Expired</span>
                        ) : (
                          <span className="text-success">Active</span>
                        )}
                      </p>
                      {link.expires_at && (
                        <p className="text-xs text-muted-foreground">
                          Expires: {formatDate(link.expires_at)}
                        </p>
                      )}
                      <p className="text-xs text-muted-foreground">
                        Viewed {link.view_count} times
                        {link.last_viewed_at && ` · Last viewed ${formatDate(link.last_viewed_at)}`}
                      </p>
                    </div>
                    {!link.is_expired && (
                      <Button size="sm" variant="outline" onClick={() => copyShareLink(link.token)}>
                        <ExternalLink className="mr-2 h-3 w-3" />
                        Copy Link
                      </Button>
                    )}
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        )}

        {/* Report Preview */}
        {report.status === 'completed' && report.data && <ReportPreview report={report} />}

        {report.status === 'completed' && !report.data && (
          <EmptyState
            title="No report data available"
            description="This report was generated but contains no data."
          />
        )}
      </div>

      {/* Share Dialog */}
      <Dialog open={showShareDialog} onOpenChange={setShowShareDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Share Report</DialogTitle>
            <DialogDescription>
              Create a shareable link for this report. You can set an expiration date and optional
              password.
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label htmlFor="expires_at">Expiration Date (Optional)</Label>
              <Input
                id="expires_at"
                type="date"
                value={shareData.expires_at}
                onChange={(e) => setShareData('expires_at', e.target.value)}
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="password">Password (Optional)</Label>
              <Input
                id="password"
                type="password"
                placeholder="Leave empty for no password"
                value={shareData.password}
                onChange={(e) => setShareData('password', e.target.value)}
              />
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowShareDialog(false)}>
              Cancel
            </Button>
            <LoadingButton onClick={handleShare} loading={isSharing}>
              Create Share Link
            </LoadingButton>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Delete Dialog */}
      <Dialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Delete Report</DialogTitle>
            <DialogDescription>
              Are you sure you want to delete &quot;{report.name}&quot;? This action cannot be
              undone.
            </DialogDescription>
          </DialogHeader>

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowDeleteDialog(false)}>
              Cancel
            </Button>
            <LoadingButton variant="destructive" onClick={handleDelete} loading={isDeleting}>
              Delete Report
            </LoadingButton>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </DashboardLayout>
  );
}
