// src/app/(dashboard)/billing/page.tsx
'use client';

import { useMemo, useState } from 'react';
import { useLocale } from 'next-intl';
import { Pencil } from 'lucide-react';
import { Button } from '@/components/ui/shared/Button';
import { Badge } from '@/components/ui/shared/Badge';
import { Card } from '@/components/ui/shared/Card';
import { Table } from '@/components/ui/shared/Table';
import { SearchBar } from '@/components/ui/shared/SearchBar';
import { useAuth } from '@/lib/hooks/useAuth';
import { hasPermission } from '@/components/shared/permissions';
import { formatAppNumber } from '@/lib/i18n/format';

type InvoiceStatus = 'paid' | 'unpaid' | 'overdue';

type Invoice = {
  id: string;
  patient: string;
  date: string;
  service: string;
  amount: number;
  paid: number;
  status: InvoiceStatus;
};

const invoices: Invoice[] = [
  { id: '#123456', patient: 'Ali Rahmani', date: '24/9/2026', service: 'Hygiene', amount: 300, paid: 0, status: 'unpaid' },
  { id: '#123457', patient: 'Neda Akbari', date: '01/10/2026', service: 'Filling', amount: 700, paid: 400, status: 'overdue' },
  { id: '#123458', patient: 'Nima Haghi', date: '09/12/2026', service: 'Extraction', amount: 450, paid: 450, status: 'paid' },
];

const statusColors = {
  paid: 'success',
  unpaid: 'warning',
  overdue: 'danger',
} as const;

const statusFilters = ['all', 'paid', 'unpaid', 'overdue'] as const;

type StatCardColor = 'blue' | 'yellow' | 'green' | 'red';

interface StatCardProps {
  title: string;
  count: number;
  amount: number;
  color: StatCardColor;
  locale: string;
}

export function BillingPage() {
  const locale = useLocale();
  const { currentOrganization } = useAuth();
  const [search, setSearch] = useState('');
  const [statusFilter, setStatusFilter] = useState<(typeof statusFilters)[number]>('all');
  const canEditBilling = hasPermission(currentOrganization, 'TAB_BILLING_EDIT');

  const stats = {
    total: { count: 235, amount: 80900 },
    unpaid: { count: 30, amount: 2800 },
    paid: { count: 190, amount: 80900 },
    overdue: { count: 235, amount: 80900 },
  };

  const filteredInvoices = useMemo(() => {
    const query = search.trim().toLowerCase();

    return invoices.filter((invoice) => {
      const matchesStatus = statusFilter === 'all' || invoice.status === statusFilter;
      const matchesSearch =
        !query ||
        invoice.patient.toLowerCase().includes(query) ||
        invoice.id.toLowerCase().includes(query) ||
        invoice.service.toLowerCase().includes(query);

      return matchesStatus && matchesSearch;
    });
  }, [search, statusFilter]);

  return (
    <div className="space-y-4 sm:space-y-6">
      <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <h1 className="text-xl sm:text-2xl font-semibold text-text-primary">Billing</h1>
        <Button
          variant="primary"
          disabled={!canEditBilling}
          className="w-full sm:w-auto shrink-0"
          title={!canEditBilling ? 'Read-only access for this organization.' : undefined}
        >
          New Invoice
        </Button>
      </div>

      <div className="grid grid-cols-2 xl:grid-cols-4 gap-3 sm:gap-4">
        <StatCard title="Total Invoices" count={stats.total.count} amount={stats.total.amount} color="blue" locale={locale} />
        <StatCard title="Unpaid Invoices" count={stats.unpaid.count} amount={stats.unpaid.amount} color="yellow" locale={locale} />
        <StatCard title="Paid Invoices" count={stats.paid.count} amount={stats.paid.amount} color="green" locale={locale} />
        <StatCard title="Overdue Invoices" count={stats.overdue.count} amount={stats.overdue.amount} color="red" locale={locale} />
      </div>

      <SearchBar
        value={search}
        onChange={setSearch}
        placeholder="Search patients..."
        actions={(
          <>
            {statusFilters.map((status) => (
              <button
                key={status}
                type="button"
                onClick={() => setStatusFilter(status)}
                className={`px-3 py-1.5 sm:px-4 sm:py-2 rounded-[var(--radius-sm)] text-xs sm:text-sm font-medium capitalize border ${
                  statusFilter === status
                    ? 'bg-primary-soft text-primary border-primary/50'
                    : 'text-text-secondary border-border/40 hover:bg-background-card/70 hover:border-border'
                }`}
              >
                {status}
              </button>
            ))}
          </>
        )}
      />

      <div className="lg:hidden space-y-3">
        {filteredInvoices.length === 0 ? (
          <div className="surface-card p-4 text-sm text-text-muted">No invoices match your filters.</div>
        ) : (
          filteredInvoices.map((invoice) => (
            <InvoiceMobileCard
              key={invoice.id}
              invoice={invoice}
              canEditBilling={canEditBilling}
            />
          ))
        )}
        <InvoicePagination className="surface-card px-3 py-3 sm:px-6" />
      </div>

      <div className="hidden lg:block">
        <Table
          headers={
            <tr>
              <th className="text-xs font-medium text-text-muted uppercase tracking-wider">
                Invoice ID
              </th>
              <th className="text-xs font-medium text-text-muted uppercase tracking-wider">
                Patient name
              </th>
              <th className="text-xs font-medium text-text-muted uppercase tracking-wider">
                Date
              </th>
              <th className="text-xs font-medium text-text-muted uppercase tracking-wider">
                Service
              </th>
              <th className="text-xs font-medium text-text-muted uppercase tracking-wider">
                Total amount
              </th>
              <th className="text-xs font-medium text-text-muted uppercase tracking-wider">
                Paid
              </th>
              <th className="text-center text-xs font-medium text-text-muted uppercase tracking-wider">
                Status
              </th>
              <th className="text-xs font-medium text-text-muted uppercase tracking-wider">
                Action
              </th>
            </tr>
          }
          body={
            <>
              {filteredInvoices.map((invoice) => (
                <tr key={invoice.id} className="hover:bg-background-secondary/45">
                  <td className="text-sm font-medium text-text-primary">{invoice.id}</td>
                  <td className="text-sm text-text-primary">{invoice.patient}</td>
                  <td className="text-sm text-text-secondary">{invoice.date}</td>
                  <td className="text-sm text-text-primary">{invoice.service}</td>
                  <td className="text-sm text-text-primary">${invoice.amount}</td>
                  <td className="text-sm text-text-primary">${invoice.paid}</td>
                  <td className="text-center align-middle">
                    <Badge variant={statusColors[invoice.status]} className="capitalize">
                      {invoice.status}
                    </Badge>
                  </td>
                  <td>
                    <InvoiceEditButton canEditBilling={canEditBilling} />
                  </td>
                </tr>
              ))}
            </>
          }
          footer={<InvoicePagination />}
        />
      </div>
    </div>
  );
}

function InvoiceMobileCard({
  invoice,
  canEditBilling,
}: {
  invoice: Invoice;
  canEditBilling: boolean;
}) {
  const remaining = invoice.amount - invoice.paid;

  return (
    <Card padding="sm" className="space-y-3">
      <div className="flex items-start justify-between gap-3">
        <div className="min-w-0">
          <p className="text-sm font-semibold text-text-primary truncate">{invoice.patient}</p>
          <p className="text-xs text-text-muted mt-0.5">{invoice.id}</p>
        </div>
        <Badge variant={statusColors[invoice.status]} fixedWidth={false} className="capitalize shrink-0">
          {invoice.status}
        </Badge>
      </div>

      <div className="flex flex-wrap gap-x-4 gap-y-1 text-sm text-text-secondary">
        <span>{invoice.service}</span>
        <span aria-hidden>·</span>
        <span>{invoice.date}</span>
      </div>

      <div className="grid grid-cols-2 sm:grid-cols-3 gap-2 text-sm">
        <div>
          <p className="text-xs text-text-muted">Total</p>
          <p className="font-medium text-text-primary">${invoice.amount}</p>
        </div>
        <div>
          <p className="text-xs text-text-muted">Paid</p>
          <p className="font-medium text-text-primary">${invoice.paid}</p>
        </div>
        <div>
          <p className="text-xs text-text-muted">Due</p>
          <p className="font-medium text-text-primary">${remaining}</p>
        </div>
      </div>

      <div className="flex justify-end pt-1 border-t border-border/60">
        <InvoiceEditButton canEditBilling={canEditBilling} />
      </div>
    </Card>
  );
}

function InvoiceEditButton({ canEditBilling }: { canEditBilling: boolean }) {
  return (
    <button
      type="button"
      className={`p-2 rounded-md ${
        canEditBilling
          ? 'text-text-secondary hover:bg-background-card/80 hover:text-text-primary'
          : 'text-text-muted cursor-not-allowed opacity-50'
      }`}
      disabled={!canEditBilling}
      title={!canEditBilling ? 'Read-only access for this organization.' : undefined}
      aria-label="Edit invoice"
    >
      <Pencil className="w-4 h-4" />
    </button>
  );
}

function InvoicePagination({ className = '' }: { className?: string }) {
  return (
    <div
      className={`flex flex-col gap-2 sm:flex-row sm:justify-between sm:items-center ${className}`.trim()}
    >
      <button type="button" className="text-sm text-text-secondary hover:text-text-primary">
        ← Previous
      </button>
      <div className="text-sm text-text-secondary text-center">Page 1 of 10</div>
      <button type="button" className="text-sm text-text-secondary hover:text-text-primary">
        Next →
      </button>
    </div>
  );
}

function StatCard({ title, count, amount, color, locale }: StatCardProps) {
  const colors: Record<StatCardColor, string> = {
    blue: '!bg-purpose-visit-bg !text-purpose-visit-fg !border-purpose-visit-border',
    yellow: '!bg-badge-warning-bg !text-badge-warning-fg !border-badge-warning-border',
    green: '!bg-badge-success-bg !text-badge-success-fg !border-badge-success-border',
    red: '!bg-badge-danger-bg !text-badge-danger-fg !border-badge-danger-border',
  };

  return (
    <Card className={`min-w-0 ${colors[color]}`}>
      <p className="text-xs sm:text-sm font-medium leading-snug">{title}</p>
      <p className="text-xl sm:text-2xl font-bold mt-1 tabular-nums">{formatAppNumber(count, locale)}</p>
      <p className="text-xs sm:text-sm font-medium mt-1 tabular-nums truncate">
        ${formatAppNumber(amount, locale)}
      </p>
    </Card>
  );
}
