'use client';

import { useCallback, useEffect, useState } from 'react';
import {
  apiListSurveys,
  apiDeleteSurvey,
  apiPauseSurvey,
  apiDuplicateSurvey,
  apiGetSurveyAnalytics,
  type ApiSurvey,
  type ApiSurveyAnalytics,
} from '@/lib/api';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { Badge } from '@/components/ui/badge';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { MoreHorizontal, Plus, Pause, Copy, Trash2, BarChart3, Download } from 'lucide-react';
import Link from 'next/link';
import { useToast } from '@/components/ui/toast';

const statusColors: Record<ApiSurvey['status'], string> = {
  draft: 'bg-gray-500',
  active: 'bg-green-500',
  paused: 'bg-orange-500',
  closed: 'bg-red-500',
};

export default function SurveysPage() {
  const [surveys, setSurveys] = useState<ApiSurvey[]>([]);
  const [loading, setLoading] = useState(true);
  const [filter, setFilter] = useState('');
  const [deleteDialog, setDeleteDialog] = useState<ApiSurvey | null>(null);
  const [analyticsDialog, setAnalyticsDialog] = useState<{
    survey: ApiSurvey;
    analytics: ApiSurveyAnalytics;
  } | null>(null);
  const { toast } = useToast();

  const loadSurveys = useCallback(async () => {
    try {
      setLoading(true);
      const { data, error } = await apiListSurveys();
      if (error) throw new Error(error);
      setSurveys(data?.surveys ?? []);
    } catch (err) {
      toast({
        title: 'Error',
        description: err instanceof Error ? err.message : 'Failed to load surveys',
        variant: 'error',
      });
    } finally {
      setLoading(false);
    }
  }, [toast]);

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

  async function handleDelete(survey: ApiSurvey) {
    try {
      const { error } = await apiDeleteSurvey(survey.id);
      if (error) throw new Error(error);
      toast({ title: 'Success', description: 'Survey deleted', variant: 'success' });
      loadSurveys();
    } catch (err) {
      toast({
        title: 'Error',
        description: err instanceof Error ? err.message : 'Failed to delete',
        variant: 'error',
      });
    }
    setDeleteDialog(null);
  }

  async function handlePause(id: string) {
    try {
      const { error } = await apiPauseSurvey(id);
      if (error) throw new Error(error);
      toast({ title: 'Success', description: 'Survey paused', variant: 'success' });
      loadSurveys();
    } catch (err) {
      toast({
        title: 'Error',
        description: err instanceof Error ? err.message : 'Failed to pause',
        variant: 'error',
      });
    }
  }

  async function handleDuplicate(survey: ApiSurvey) {
    try {
      const { error } = await apiDuplicateSurvey(survey.id);
      if (error) throw new Error(error);
      toast({ title: 'Success', description: 'Survey duplicated', variant: 'success' });
      loadSurveys();
    } catch (err) {
      toast({
        title: 'Error',
        description: err instanceof Error ? err.message : 'Failed to duplicate',
        variant: 'error',
      });
    }
  }

  async function viewAnalytics(survey: ApiSurvey) {
    try {
      const { data, error } = await apiGetSurveyAnalytics(survey.id);
      if (error) throw new Error(error);
      if (data) {
        setAnalyticsDialog({ survey, analytics: data });
      }
    } catch (err) {
      toast({
        title: 'Error',
        description: err instanceof Error ? err.message : 'Failed to load analytics',
        variant: 'error',
      });
    }
  }

  async function exportCSV(survey: ApiSurvey) {
    try {
      const csv = await import('@/lib/api').then(m => m.apiExportSurveyCSV(survey.id));
      const blob = new Blob([csv], { type: 'text/csv' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `${survey.id}_responses.csv`;
      a.click();
      URL.revokeObjectURL(url);
      toast({ title: 'Success', description: 'CSV exported', variant: 'success' });
    } catch (err) {
      toast({
        title: 'Error',
        description: err instanceof Error ? err.message : 'Failed to export',
        variant: 'error',
      });
    }
  }

  const filteredSurveys = surveys.filter(
    s =>
      s.title.toLowerCase().includes(filter.toLowerCase()) ||
      (s.description?.toLowerCase() || '').includes(filter.toLowerCase())
  );

  if (loading) {
    return (
      <div className="container mx-auto py-8">
        <div className="animate-pulse space-y-4">
          <div className="h-8 w-48 bg-muted rounded" />
          <div className="h-64 bg-muted rounded" />
        </div>
      </div>
    );
  }

  return (
    <div className="container mx-auto py-8 space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold">Surveys</h1>
          <p className="text-muted-foreground">
            Create and manage in-app surveys with conditional logic
          </p>
        </div>
        <Link href="/surveys/new">
          <Button>
            <Plus className="mr-2 h-4 w-4" />
            New Survey
          </Button>
        </Link>
      </div>

      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <div>
              <CardTitle>All Surveys</CardTitle>
              <CardDescription>{surveys.length} total surveys</CardDescription>
            </div>
            <Input
              placeholder="Filter surveys..."
              value={filter}
              onChange={e => setFilter(e.target.value)}
              className="w-64"
            />
          </div>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Title</TableHead>
                <TableHead>Status</TableHead>
                <TableHead>Questions</TableHead>
                <TableHead>Metrics</TableHead>
                <TableHead>Incentive</TableHead>
                <TableHead>Created</TableHead>
                <TableHead className="w-12" />
              </TableRow>
            </TableHeader>
            <TableBody>
              {filteredSurveys.map(survey => (
                <TableRow key={survey.id}>
                  <TableCell>
                    <div className="font-medium">{survey.title}</div>
                    <div className="text-sm text-muted-foreground line-clamp-1">
                      {survey.description || 'No description'}
                    </div>
                  </TableCell>
                  <TableCell>
                    <Badge className={statusColors[survey.status]}>{survey.status}</Badge>
                  </TableCell>
                  <TableCell>{survey.questions.length} questions</TableCell>
                  <TableCell>
                    <div className="text-sm space-y-1">
                      <div>Starts: {survey.metrics.starts}</div>
                      <div className="text-muted-foreground">
                        Completion:{' '}
                        {(
                          (survey.metrics.completions / Math.max(survey.metrics.starts, 1)) *
                          100
                        ).toFixed(1)}
                        %
                      </div>
                    </div>
                  </TableCell>
                  <TableCell>
                    {survey.incentive ? (
                      <Badge variant="outline">
                        {survey.incentive.amount} {survey.incentive.type}
                      </Badge>
                    ) : (
                      <span className="text-muted-foreground">None</span>
                    )}
                  </TableCell>
                  <TableCell>{new Date(survey.createdAt).toLocaleDateString()}</TableCell>
                  <TableCell>
                    <DropdownMenu>
                      <DropdownMenuTrigger asChild>
                        <Button variant="ghost" size="icon">
                          <MoreHorizontal className="h-4 w-4" />
                        </Button>
                      </DropdownMenuTrigger>
                      <DropdownMenuContent align="end">
                        <DropdownMenuItem asChild>
                          <Link href={`/surveys/${survey.id}`}>Edit</Link>
                        </DropdownMenuItem>
                        <DropdownMenuItem onClick={() => viewAnalytics(survey)}>
                          <BarChart3 className="mr-2 h-4 w-4" />
                          View Analytics
                        </DropdownMenuItem>
                        <DropdownMenuItem onClick={() => exportCSV(survey)}>
                          <Download className="mr-2 h-4 w-4" />
                          Export CSV
                        </DropdownMenuItem>
                        {survey.status === 'active' && (
                          <DropdownMenuItem onClick={() => handlePause(survey.id)}>
                            <Pause className="mr-2 h-4 w-4" />
                            Pause
                          </DropdownMenuItem>
                        )}
                        <DropdownMenuItem onClick={() => handleDuplicate(survey)}>
                          <Copy className="mr-2 h-4 w-4" />
                          Duplicate
                        </DropdownMenuItem>
                        <DropdownMenuItem
                          className="text-destructive"
                          onClick={() => setDeleteDialog(survey)}
                        >
                          <Trash2 className="mr-2 h-4 w-4" />
                          Delete
                        </DropdownMenuItem>
                      </DropdownMenuContent>
                    </DropdownMenu>
                  </TableCell>
                </TableRow>
              ))}
              {filteredSurveys.length === 0 && (
                <TableRow>
                  <TableCell colSpan={7} className="text-center py-8 text-muted-foreground">
                    {filter ? 'No surveys match your filter' : 'No surveys yet'}
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      <Dialog open={!!deleteDialog} onOpenChange={() => setDeleteDialog(null)}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Delete Survey</DialogTitle>
            <DialogDescription>
              Are you sure you want to delete &quot;{deleteDialog?.title}&quot;? This action cannot
              be undone.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="outline" onClick={() => setDeleteDialog(null)}>
              Cancel
            </Button>
            <Button
              variant="destructive"
              onClick={() => deleteDialog && handleDelete(deleteDialog)}
            >
              Delete
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog open={!!analyticsDialog} onOpenChange={() => setAnalyticsDialog(null)}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>Survey Analytics: {analyticsDialog?.survey.title}</DialogTitle>
            <DialogDescription>
              {analyticsDialog?.analytics.totalStarts} starts,{' '}
              {analyticsDialog?.analytics.totalCompletions} completions
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="grid grid-cols-3 gap-4">
              <Card>
                <CardHeader className="pb-2">
                  <CardTitle className="text-2xl">
                    {analyticsDialog?.analytics.completionRate.toFixed(1)}%
                  </CardTitle>
                  <CardDescription>Completion Rate</CardDescription>
                </CardHeader>
              </Card>
              <Card>
                <CardHeader className="pb-2">
                  <CardTitle className="text-2xl">
                    {Math.round(analyticsDialog?.analytics.avgTimeSeconds || 0)}s
                  </CardTitle>
                  <CardDescription>Avg. Time</CardDescription>
                </CardHeader>
              </Card>
              <Card>
                <CardHeader className="pb-2">
                  <CardTitle className="text-2xl">
                    {analyticsDialog?.survey.metrics.incentiveClaims}
                  </CardTitle>
                  <CardDescription>Incentives Claimed</CardDescription>
                </CardHeader>
              </Card>
            </div>
            {analyticsDialog?.analytics.questionAnalytics.map(qa => (
              <Card key={qa.questionId}>
                <CardHeader className="pb-2">
                  <CardTitle className="text-sm">
                    Q: {analyticsDialog.survey.questions.find(q => q.id === qa.questionId)?.text}
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="text-sm text-muted-foreground">
                    {qa.totalResponses} responses
                    {qa.average !== undefined && ` • Avg: ${qa.average.toFixed(2)}`}
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}
