"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { Plus, CircleQuestionMark, Filter } from "lucide-react";
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
import { DialogDescription, DialogFooter }    from "@/components/ui/dialog";
import { DialogHeader, DialogTrigger }        from "@/components/ui/dialog";
import { Drawer, DrawerClose, DrawerContent } from "@/components/ui/drawer";
import { DrawerDescription, DrawerFooter }    from "@/components/ui/drawer";
import { DrawerHeader, DrawerTitle }          from "@/components/ui/drawer";
import { DrawerTrigger }                      from "@/components/ui/drawer";
import { useMediaQuery }                      from '@/hooks/use-media-query';
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import { EmptyDescription, EmptyMedia }   from "@/components/ui/empty";
import Link from "next/link";

import type { TradingSystem } from "@/generated/prisma/client";

interface TradingSystemsViewProps {
  initialSystems: (TradingSystem & { _count: { trades: number } })[];
  count: number;
}

export function TradingSystemsView({ initialSystems, count }: TradingSystemsViewProps) {
  const router = useRouter();
  const [open, setOpen] = useState(false);
  const [editingSystem, setEditingSystem] = useState<TradingSystem | null>(null);
  const [deletingSystem, setDeletingSystem] = useState<TradingSystem | null>(null);
  const [formData, setFormData] = useState({ name: "", description: "" });
  const [loading, setLoading] = useState(false);
  const [isFormValid, setIsFormValid] = useState(false);
  const mq = useMediaQuery();

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);

    try {
      const url = "/api/user/trading-system";
      const method = editingSystem ? "PUT" : "POST";
      const body = editingSystem ? { ...formData, id: editingSystem.id } : formData;

      const res = await fetch(url, {
        method,
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body),
      });

      if (res.ok) {
        router.refresh();
        setOpen(false);
        setEditingSystem(null);
        setFormData({ name: "", description: "" });
      }
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = (system: TradingSystem) => {
    setDeletingSystem(system);
  };

  const confirmDelete = async () => {
    if (!deletingSystem) return;
    setLoading(true);
    try {
      const res = await fetch(`/api/user/trading-system?id=${deletingSystem.id}`, {
        method: "DELETE",
      });
      if (res.ok) {
        router.refresh();
        setDeletingSystem(null);
      }
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  const openEdit = (system: TradingSystem) => {
    setEditingSystem(system);
    setFormData({ name: system.name, description: system.description || "" });
    setOpen(true);
    setIsFormValid(true);
  };

  const openNew = () => {
    setEditingSystem(null);
    setFormData({ name: "", description: "" });
    setOpen(true);
    setIsFormValid(false);
  };

  const FormContent = (
    <div className="grid gap-4 py-4">
      <div className="grid gap-2">
        <Label htmlFor="name">Name</Label>
        <Input
          id="name"
          required
          value={formData.name}
          onChange={(e) => setFormData({ ...formData, name: e.target.value })}
          placeholder="e.g. Trend Following"
        />
      </div>
      <div className="grid gap-2">
        <Label htmlFor="description">Description</Label>
        <Textarea
          id="description"
          value={formData.description}
          onChange={(e) => setFormData({ ...formData, description: e.target.value })}
          placeholder="Describe your trading system..."
          rows={3}
        />
      </div>
    </div>
  );

  return (
    <div className="space-y-6">
      <div className="mb-6">
        <div className="flex justify-between items-center gap-4">
          <div>
            <h1 className="text-3xl font-bold tracking-tight">Trading Systems</h1>
            {/* <p className="text-muted-foreground"></p> */}
          </div>

          <Button className="flex items-center gap-1 cursor-pointer" onClick={openNew}>
            <Plus className="h-4 w-4" />
            Add New
          </Button>
        </div>

        {mq?.desktop ? (
          <Dialog open={open} onOpenChange={setOpen}>
            <DialogContent showCloseButton={false} className="sm:max-w-106.25 overflow-hidden max-h-[calc(100vh-2.5rem)] flex flex-col px-0! pb-0! gap-0">
              <div className="flex-1 overflow-y-auto px-6">
                <DialogHeader className="pb-6 pt-6">
                  <DialogTitle>{editingSystem ? "Edit Trading System" : "Add New Trading System"}</DialogTitle>
                  <DialogDescription>
                    {editingSystem ? "Edit the details of your trading system." : "Enter the details of your new trading system."}
                  </DialogDescription>
                </DialogHeader>
                <form id="trading-system-form" onSubmit={handleSubmit} onChange={(e) => setIsFormValid(e.currentTarget.checkValidity())} className="pb-4">
                  {FormContent}
                </form>
              </div>
              <div className="px-6 py-4 flex justify-between items-center gap-3 border-t border-border">
                <div className="">
                  <Button asChild type="button" variant="ghost" size="icon" className="bg-transparent hover:bg-transparent w-auto h-auto p-1 rounded-full">
                    <Link href="#">
                      <CircleQuestionMark />
                    </Link>
                  </Button>
                </div>
                <div className="inline-flex gap-3">
                  <Button className="cursor-pointer" variant="outline" type="button" onClick={() => setOpen(false)}>Cancel</Button>
                  <Button className="cursor-pointer" type="submit" form="trading-system-form" disabled={!isFormValid || loading}>
                    {loading ? "Saving..." : "Save"}
                  </Button>
                </div>
              </div>
            </DialogContent>
          </Dialog>
        ) : (
          <Drawer open={open} onOpenChange={setOpen}>
            <DrawerContent className="h-auto! max-h-[98vh]!">
              <form id="trading-system-form" onSubmit={handleSubmit} onChange={(e) => setIsFormValid(e.currentTarget.checkValidity())} className="block overflow-y-auto px-4 pb-6">
                <DrawerHeader className="text-left pb-6">
                  <DrawerTitle>{editingSystem ? "Edit Trading System" : "Add New Trading System"}</DrawerTitle>
                  <DrawerDescription>
                    {editingSystem ? "Edit the details of your trading system." : "Enter the details of your new trading system."}
                  </DrawerDescription>
                </DrawerHeader>
                {FormContent}
              </form>
              <DrawerFooter className="grid grid-cols-2 gap-3 border-t border-border py-3">
                <DrawerClose asChild>
                  <Button className="cursor-pointer" variant="outline">Cancel</Button>
                </DrawerClose>
                <Button className="cursor-pointer" type="submit" form="trading-system-form" disabled={!isFormValid || loading}>
                  {loading ? "Saving..." : "Save"}
                </Button>
              </DrawerFooter>
            </DrawerContent>
          </Drawer>
        )}

      </div>

      <Dialog open={!!deletingSystem} onOpenChange={(open) => !open && setDeletingSystem(null)}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Delete Trading System</DialogTitle>
            <DialogDescription>
              Are you sure you want to delete "{deletingSystem?.name}"? This action cannot be undone.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="outline" onClick={() => setDeletingSystem(null)}>Cancel</Button>
            <Button variant="destructive" onClick={confirmDelete} disabled={loading}>
              {loading ? "Deleting..." : "Delete"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {initialSystems.length === 0 && (
        <div className="w-full flex justify-center mt-20">
          <Empty>
            <EmptyMedia variant="icon"><Filter /></EmptyMedia>
            <EmptyHeader>
              <EmptyTitle>No trading systems found</EmptyTitle>
              <EmptyDescription>Create one to get started.</EmptyDescription>
            </EmptyHeader>
          </Empty>
        </div>
      )}
    
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
        {initialSystems.map((system) => (
          <div
            key={system.id}
            className="border rounded-lg p-4 bg-card text-card-foreground"
          >
            <div className="flex justify-between items-start mb-2">
              <h3 className="font-semibold text-lg">{system.name}</h3>
              <div className="flex gap-2">
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => openEdit(system)}
                  className="h-8 px-2 text-blue-600 hover:text-blue-800 hover:bg-blue-50"
                >
                  Edit
                </Button>
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => handleDelete(system)}
                  className="h-8 px-2 text-red-600 hover:text-red-800 hover:bg-red-50"
                >
                  Delete
                </Button>
              </div>
            </div>
            <p className="text-muted-foreground text-sm mb-4 line-clamp-2 truncate">
              {system.description || "No description"}
            </p>
            <div className="flex justify-between items-center text-xs text-muted-foreground border-t pt-3">
              <span>{system._count.trades} Trades</span>
              <span>{new Date(system.createdAt).toLocaleDateString()}</span>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}