"use client";

import EmailClassificationRow, {
  CLASSIFICATIONS,
} from "@/components/pages/shield/EmailClassificationRow";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { Command, CommandItem } from "@/components/ui/command";
import { Input } from "@/components/ui/input";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import {
  Table,
  TableBody,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { toast } from "@/components/ui/use-toast";
import {
  createEmailClassification,
  fetchEmailClassifications,
} from "@/lib/actions";
import { EmailClassification } from "@/lib/db";
import { useEffect, useState } from "react";

export default function Classifications() {
  const [loaded, setLoaded] = useState(false);
  const [domains, setDomains] = useState([] as EmailClassification[]);
  const [domainDraft, setDomainDraft] = useState("");
  const [classificationDraft, setClassificationDraft] = useState<string>("");
  const [classificationOpen, setClassificationOpen] = useState(false);

  useEffect(() => {
    fetchEmailClassifications().then((domains) => {
      setDomains(domains.sort((a, b) => a._id.localeCompare(b._id)));
      setLoaded(true);
    });
  }, []);

  return (
    <Card>
      <Table>
        <TableHeader>
          <TableRow>
            <TableHead>Domain</TableHead>
            <TableHead>Classification</TableHead>
            <TableHead className="flex flex-row items-center justify-between gap-2 pr-1">
              <span>Action</span>
              <div className="text-end pr-2">
                <AlertDialog>
                  <AlertDialogTrigger asChild>
                    <Button disabled={!loaded}>Add</Button>
                  </AlertDialogTrigger>
                  <AlertDialogContent>
                    <AlertDialogHeader>
                      <AlertDialogTitle>Create classification</AlertDialogTitle>
                      <AlertDialogDescription className="flex flex-row gap-1">
                        <Input
                          value={domainDraft}
                          onChange={(e) =>
                            setDomainDraft(e.currentTarget.value)
                          }
                          placeholder="reddit.com"
                        />
                        <Popover
                          open={classificationOpen}
                          onOpenChange={setClassificationOpen}
                        >
                          <PopoverTrigger asChild>
                            <Button
                              variant="outline"
                              role="combobox"
                              aria-expanded={classificationOpen}
                            >
                              {classificationDraft || "Classification"}
                            </Button>
                          </PopoverTrigger>
                          <PopoverContent>
                            <Command>
                              {CLASSIFICATIONS.map((c) => (
                                <CommandItem
                                  key={c}
                                  onSelect={() => {
                                    setClassificationDraft(c);
                                    setClassificationOpen(false);
                                  }}
                                >
                                  {c}
                                </CommandItem>
                              ))}
                            </Command>
                          </PopoverContent>
                        </Popover>
                      </AlertDialogDescription>
                    </AlertDialogHeader>
                    <AlertDialogFooter>
                      <AlertDialogCancel>Cancel</AlertDialogCancel>
                      <AlertDialogAction
                        disabled={!domainDraft || !classificationDraft}
                        onClick={async () => {
                          try {
                            await createEmailClassification(
                              domainDraft,
                              classificationDraft
                            );
                            setDomains([
                              ...domains,
                              {
                                _id: domainDraft,
                                classification: classificationDraft,
                              },
                            ]);
                            setDomainDraft("");
                            setClassificationDraft("");
                            setClassificationOpen(false);
                            toast({
                              title: "Classification created",
                            });
                          } catch (e) {
                            toast({
                              title: "Failed to create classification",
                              description: String(e),
                              variant: "destructive",
                            });
                          }
                        }}
                      >
                        Create
                      </AlertDialogAction>
                    </AlertDialogFooter>
                  </AlertDialogContent>
                </AlertDialog>
              </div>
            </TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {domains.map((domain) => (
            <EmailClassificationRow
              key={domain._id}
              domain={domain._id}
              classification={domain.classification}
            />
          ))}
        </TableBody>
      </Table>
    </Card>
  );
}
