'use client';

import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { ColumnDef } from '@tanstack/react-table';
import Link from 'next/link';
import { MoreHorizontal, Mail, MailOpen, TrendingUp } from 'lucide-react';

import { onboardingEmailsApi } from '@/lib/api';
import type { OnboardingEmail } from '@/lib/api';
import { DataTable } from '@/components/data-table';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';

const emailTypeLabels: Record<string, string> = {
  no_residence: 'No Residence',
  no_tasks: 'No Tasks',
};

const emailTypeColors: Record<string, 'default' | 'secondary' | 'outline'> = {
  no_residence: 'default',
  no_tasks: 'secondary',
};

const columns: ColumnDef<OnboardingEmail>[] = [
  {
    accessorKey: 'id',
    header: 'ID',
    cell: ({ row }) => (
      <span className="font-mono text-sm">{row.original.id}</span>
    ),
  },
  {
    accessorKey: 'user_name',
    header: 'User',
    cell: ({ row }) => (
      <div>
        <div className="font-medium">{row.original.user_name || 'Unknown'}</div>
        <div className="text-sm text-muted-foreground">{row.original.user_email}</div>
      </div>
    ),
  },
  {
    accessorKey: 'email_type',
    header: 'Type',
    cell: ({ row }) => (
      <Badge variant={emailTypeColors[row.original.email_type] || 'outline'}>
        {emailTypeLabels[row.original.email_type] || row.original.email_type}
      </Badge>
    ),
  },
  {
    accessorKey: 'sent_at',
    header: 'Sent',
    cell: ({ row }) => {
      const date = new Date(row.original.sent_at);
      return (
        <div>
          <div>{date.toLocaleDateString()}</div>
          <div className="text-sm text-muted-foreground">{date.toLocaleTimeString()}</div>
        </div>
      );
    },
  },
  {
    accessorKey: 'opened_at',
    header: 'Opened',
    cell: ({ row }) => {
      if (row.original.opened_at) {
        const date = new Date(row.original.opened_at);
        return (
          <div className="flex items-center gap-2">
            <MailOpen className="h-4 w-4 text-green-500" />
            <div>
              <div>{date.toLocaleDateString()}</div>
              <div className="text-sm text-muted-foreground">{date.toLocaleTimeString()}</div>
            </div>
          </div>
        );
      }
      return (
        <div className="flex items-center gap-2 text-muted-foreground">
          <Mail className="h-4 w-4" />
          <span>Not opened</span>
        </div>
      );
    },
  },
  {
    accessorKey: 'tracking_id',
    header: 'Tracking ID',
    cell: ({ row }) => (
      <span className="font-mono text-xs text-muted-foreground">
        {row.original.tracking_id.substring(0, 12)}...
      </span>
    ),
  },
  {
    id: 'actions',
    cell: ({ row }) => {
      const email = row.original;
      return (
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="ghost" className="h-8 w-8 p-0">
              <span className="sr-only">Open menu</span>
              <MoreHorizontal className="h-4 w-4" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            <DropdownMenuLabel>Actions</DropdownMenuLabel>
            <DropdownMenuItem asChild>
              <Link href={`/users/${email.user_id}`}>View user</Link>
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      );
    },
  },
];

function StatsCards() {
  const { data: stats, isLoading } = useQuery({
    queryKey: ['onboarding-emails-stats'],
    queryFn: () => onboardingEmailsApi.getStats(),
  });

  if (isLoading) {
    return (
      <div className="grid gap-4 md:grid-cols-3 lg:grid-cols-5">
        {[...Array(5)].map((_, i) => (
          <Card key={i}>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Loading...</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">-</div>
            </CardContent>
          </Card>
        ))}
      </div>
    );
  }

  return (
    <div className="grid gap-4 md:grid-cols-3 lg:grid-cols-5">
      <Card>
        <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
          <CardTitle className="text-sm font-medium">Total Sent</CardTitle>
          <Mail className="h-4 w-4 text-muted-foreground" />
        </CardHeader>
        <CardContent>
          <div className="text-2xl font-bold">{stats?.total_sent ?? 0}</div>
          <p className="text-xs text-muted-foreground">
            {stats?.total_opened ?? 0} opened
          </p>
        </CardContent>
      </Card>

      <Card>
        <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
          <CardTitle className="text-sm font-medium">Overall Open Rate</CardTitle>
          <TrendingUp className="h-4 w-4 text-muted-foreground" />
        </CardHeader>
        <CardContent>
          <div className="text-2xl font-bold">
            {stats?.overall_open_rate?.toFixed(1) ?? 0}%
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
          <CardTitle className="text-sm font-medium">No Residence</CardTitle>
          <Badge variant="default" className="text-xs">Type 1</Badge>
        </CardHeader>
        <CardContent>
          <div className="text-2xl font-bold">{stats?.no_residence_total ?? 0}</div>
          <p className="text-xs text-muted-foreground">
            {stats?.no_residence_open_rate?.toFixed(1) ?? 0}% open rate
          </p>
        </CardContent>
      </Card>

      <Card>
        <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
          <CardTitle className="text-sm font-medium">No Tasks</CardTitle>
          <Badge variant="secondary" className="text-xs">Type 2</Badge>
        </CardHeader>
        <CardContent>
          <div className="text-2xl font-bold">{stats?.no_tasks_total ?? 0}</div>
          <p className="text-xs text-muted-foreground">
            {stats?.no_tasks_open_rate?.toFixed(1) ?? 0}% open rate
          </p>
        </CardContent>
      </Card>

      <Card>
        <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
          <CardTitle className="text-sm font-medium">Total Opened</CardTitle>
          <MailOpen className="h-4 w-4 text-green-500" />
        </CardHeader>
        <CardContent>
          <div className="text-2xl font-bold">{stats?.total_opened ?? 0}</div>
          <p className="text-xs text-muted-foreground">
            of {stats?.total_sent ?? 0} sent
          </p>
        </CardContent>
      </Card>
    </div>
  );
}

export default function OnboardingEmailsPage() {
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [emailType, setEmailType] = useState<string>('all');
  const [openedFilter, setOpenedFilter] = useState<string>('all');

  const { data, isLoading } = useQuery({
    queryKey: ['onboarding-emails', { page, page_size: pageSize, email_type: emailType, opened: openedFilter }],
    queryFn: () => onboardingEmailsApi.list({
      page,
      page_size: pageSize,
      email_type: emailType !== 'all' ? emailType : undefined,
      opened: openedFilter !== 'all' ? openedFilter as 'true' | 'false' : undefined,
    }),
  });

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold">Onboarding Emails</h1>
        <p className="text-muted-foreground">
          Track automated onboarding email campaigns and open rates
        </p>
      </div>

      <StatsCards />

      <div className="flex gap-4">
        <div className="w-48">
          <Select value={emailType} onValueChange={(value) => { setEmailType(value); setPage(1); }}>
            <SelectTrigger>
              <SelectValue placeholder="Email type" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">All Types</SelectItem>
              <SelectItem value="no_residence">No Residence</SelectItem>
              <SelectItem value="no_tasks">No Tasks</SelectItem>
            </SelectContent>
          </Select>
        </div>
        <div className="w-48">
          <Select value={openedFilter} onValueChange={(value) => { setOpenedFilter(value); setPage(1); }}>
            <SelectTrigger>
              <SelectValue placeholder="Opened status" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">All Statuses</SelectItem>
              <SelectItem value="true">Opened</SelectItem>
              <SelectItem value="false">Not Opened</SelectItem>
            </SelectContent>
          </Select>
        </div>
      </div>

      <DataTable
        columns={columns}
        data={data?.data ?? []}
        totalCount={data?.total ?? 0}
        page={page}
        pageSize={pageSize}
        onPageChange={setPage}
        onPageSizeChange={(size) => {
          setPageSize(size);
          setPage(1);
        }}
        isLoading={isLoading}
      />
    </div>
  );
}
