'use client'

import { useState } from 'react'
import { useRouter } from 'next/navigation'
import Link from 'next/link'
import { Account } from '@/generated/prisma/client'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import {
  DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { MoreHorizontal, Pencil, Trash2, EyeOff, Eye, TrendingUp } from 'lucide-react'
import { AccountBadge } from './AccountBadge'
import { CreateAccountDialog } from './CreateAccountDialog'
import { RecordValueDialog } from './RecordValueDialog'
import { formatCents } from '@/lib/utils/currency'

export function AccountCard({ account }: { account: Account }) {
  const router = useRouter()
  const [editOpen, setEditOpen] = useState(false)
  const [recordOpen, setRecordOpen] = useState(false)

  async function handleToggleActive() {
    await fetch(`/api/accounts/${account.id}`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ isActive: !account.isActive }),
    })
    router.refresh()
  }

  async function handleDelete() {
    if (!confirm(`Delete "${account.name}"? This cannot be undone.`)) return
    await fetch(`/api/accounts/${account.id}`, { method: 'DELETE' })
    router.refresh()
  }

  return (
    <>
      <Card className={account.isActive ? '' : 'opacity-60'}>
        <CardHeader className="flex flex-row items-start justify-between space-y-0 pb-2">
          <div className="space-y-1 min-w-0">
            <CardTitle className="text-base truncate">
              <Link href={`/accounts/${account.id}`} className="hover:underline">
                {account.name}
              </Link>
            </CardTitle>
            {account.institution && (
              <p className="text-xs text-muted-foreground truncate">{account.institution}</p>
            )}
          </div>
          <div className="flex items-center gap-1 shrink-0 ml-2">
            <AccountBadge type={account.type} />
            <DropdownMenu>
              <DropdownMenuTrigger className="inline-flex h-7 w-7 items-center justify-center rounded-md hover:bg-accent transition-colors">
                <MoreHorizontal className="h-4 w-4" />
                <span className="sr-only">Account actions</span>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end">
                <DropdownMenuItem onClick={() => setEditOpen(true)}>
                  <Pencil className="h-4 w-4 mr-2" />Edit
                </DropdownMenuItem>
                {account.type === 'INVESTMENT' && (
                  <DropdownMenuItem onClick={() => setRecordOpen(true)}>
                    <TrendingUp className="h-4 w-4 mr-2" />Record value
                  </DropdownMenuItem>
                )}
                <DropdownMenuItem onClick={handleToggleActive}>
                  {account.isActive
                    ? <><EyeOff className="h-4 w-4 mr-2" />Deactivate</>
                    : <><Eye className="h-4 w-4 mr-2" />Activate</>
                  }
                </DropdownMenuItem>
                <DropdownMenuSeparator />
                <DropdownMenuItem
                  onClick={handleDelete}
                  className="text-destructive focus:text-destructive"
                >
                  <Trash2 className="h-4 w-4 mr-2" />
                  Delete
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </div>
        </CardHeader>
        <CardContent>
          <p className="text-2xl font-bold tabular-nums">
            {formatCents(account.currentBalanceCents)}
          </p>
          {!account.isActive && (
            <p className="text-xs text-muted-foreground mt-1">Inactive</p>
          )}
        </CardContent>
      </Card>

      <CreateAccountDialog open={editOpen} onOpenChange={setEditOpen} account={account} />
      {account.type === 'INVESTMENT' && (
        <RecordValueDialog
          open={recordOpen}
          onOpenChange={setRecordOpen}
          accountId={account.id}
          accountName={account.name}
        />
      )}
    </>
  )
}
