import { IS_PLATFORM, useParams } from 'common'
import saveAs from 'file-saver'
import { Download, Settings } from 'lucide-react'
import Link from 'next/link'
import { usePathname } from 'next/navigation'
import Papa from 'papaparse'
import { useEffect, useState } from 'react'
import { toast } from 'sonner'
import {
  Button,
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogSection,
  DialogTitle,
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from 'ui'

import { QuerySearchParamsType } from '../UnifiedLogs.types'
import { ButtonTooltip } from '@/components/ui/ButtonTooltip'
import { useGetUnifiedLogsMutation } from '@/data/logs/get-unified-logs'

const DEFAULT_NUM_ROWS = '100'
const DEFAULT_DURATION = '1'

interface DownloadLogsButtonProps {
  searchParameters: QuerySearchParamsType
}

export const DownloadLogsButton = ({ searchParameters }: DownloadLogsButtonProps) => {
  const { ref } = useParams()
  const pathname = usePathname()
  const isLogs = pathname?.includes?.('/logs') ?? false
  const [numRows, setNumRows] = useState(DEFAULT_NUM_ROWS)
  const [numHours, setNumHours] = useState(DEFAULT_NUM_ROWS)
  const [selectedFormat, setSelectedFormat] = useState<'csv' | 'json'>()

  const { mutate: retrieveLogs, isPending } = useGetUnifiedLogsMutation({
    onSuccess: (res) => {
      if (selectedFormat === 'json') {
        const blob = new Blob([JSON.stringify(res, null, 2)], { type: 'text/json;charset=utf-8;' })
        saveAs(blob, `briven_logs.json`)
        toast.success('Downloading logs as JSON')
      } else {
        if (res.length === 0) return
        const headers = Object.keys(res[0])
        const formattedResults = res.map((row) => {
          const r: Record<string, unknown> = { ...row }
          Object.keys(row).forEach((x) => {
            const k = x as keyof typeof row
            if (typeof row[k] === 'object') r[x] = JSON.stringify(row[k])
          })
          return r
        })
        const csv = Papa.unparse(formattedResults, { columns: headers })
        const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' })
        saveAs(blob, `briven_logs.csv`)
        toast.success('Downloading logs as CSV')
      }

      setSelectedFormat(undefined)
    },
  })

  const onExportData = () => {
    if (!ref) return console.error('Project ref is required')

    const hasSpecificTimeRange = 'date' in searchParameters
    retrieveLogs({
      projectRef: ref,
      search: searchParameters,
      limit: Number(numRows),
      hoursAgo: !hasSpecificTimeRange ? Number(numHours) : undefined,
    })
  }

  useEffect(() => {
    if (!!selectedFormat) {
      setNumRows(DEFAULT_NUM_ROWS)
      setNumHours(DEFAULT_DURATION)
    }
  }, [selectedFormat])

  return (
    <>
      <DropdownMenu>
        <DropdownMenuTrigger asChild>
          <ButtonTooltip
            type="default"
            className="w-[26px]"
            icon={<Download className="text-foreground" />}
            tooltip={{ content: { side: 'bottom', text: 'Download logs' } }}
          />
        </DropdownMenuTrigger>
        <DropdownMenuContent align="end" className="w-44">
          {isLogs && IS_PLATFORM && (
            <DropdownMenuItem asChild className="gap-x-2">
              <Link href={`/project/${ref}/settings/log-drains`}>
                <Settings size={14} />
                <p>Add a Log Drain</p>
              </Link>
            </DropdownMenuItem>
          )}
          <DropdownMenuItem onClick={() => setSelectedFormat('csv')} className="gap-x-2">
            <Download size={14} />
            <p>Download as CSV</p>
          </DropdownMenuItem>
          <DropdownMenuItem onClick={() => setSelectedFormat('json')} className="gap-x-2">
            <Download size={14} />
            <p>Download as JSON</p>
          </DropdownMenuItem>
        </DropdownMenuContent>
      </DropdownMenu>
      <Dialog
        open={!!selectedFormat}
        onOpenChange={(open) => {
          if (!open) setSelectedFormat(undefined)
        }}
      >
        <DialogContent size="small">
          <DialogHeader className="border-b">
            <DialogTitle>Download logs as {selectedFormat?.toLocaleUpperCase()}</DialogTitle>
            <DialogDescription>
              Export your logs with the currently applied filters
            </DialogDescription>
          </DialogHeader>
          <DialogSection className="flex flex-col gap-y-2">
            <div className="flex justify-between gap-x-2">
              <p className="text-sm mb-2">Result limit for export</p>
              <Select value={numRows} onValueChange={setNumRows}>
                <SelectTrigger className="w-24">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="100">100</SelectItem>
                  <SelectItem value="500">500</SelectItem>
                  <SelectItem value="1000">1000</SelectItem>
                </SelectContent>
              </Select>
            </div>
            {!('date' in searchParameters) && (
              <div className="flex justify-between gap-x-2">
                <p className="text-sm mb-2">Duration to retrieve</p>
                <Select value={numHours} onValueChange={setNumHours}>
                  <SelectTrigger className="w-36">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="1">1 hour ago</SelectItem>
                    <SelectItem value="12">12 hours ago</SelectItem>
                    <SelectItem value="24">24 hours ago</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            )}
          </DialogSection>
          <DialogFooter>
            <Button
              type="default"
              disabled={isPending}
              onClick={() => setSelectedFormat(undefined)}
            >
              Cancel
            </Button>
            <Button type="primary" loading={isPending} onClick={onExportData}>
              Export
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  )
}
