'use client';

import { useState, useEffect } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';

import { Loader2, Send, CreditCard } from 'lucide-react';
import { useForm, Controller } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { format } from 'date-fns';

import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { FormErrorSummary } from '@/components/forms/form-error-summary';
import { useFormScrollToError } from '@/hooks/use-form-scroll-to-error';
import { PermissionGate } from '@/components/shared/permission-gate';
import { toast } from 'sonner';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { DatePicker } from '@/components/ui/date-picker';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { apiFetch } from '@/lib/api/client';
import { toastError } from '@/lib/api/toast-error';
import { useMobileChrome } from '@/components/layout/mobile/mobile-layout-provider';
import { recordPaymentSchema, type RecordPaymentInput } from '@/lib/validators/invoices';

const STATUS_COLORS: Record<string, string> = {
  draft: 'bg-gray-100 text-gray-700 border-gray-200',
  sent: 'bg-blue-100 text-blue-700 border-blue-200',
  paid: 'bg-green-100 text-green-700 border-green-200',
  overdue: 'bg-red-100 text-red-700 border-red-200',
  cancelled: 'bg-gray-100 text-gray-500 border-gray-200',
};

// Display labels for snake_case enum values stored in the DB.
const PAYMENT_METHOD_LABELS: Record<string, string> = {
  bank_transfer: 'Bank transfer',
  credit_card: 'Credit card',
  cash: 'Cash',
  cheque: 'Cheque',
  check: 'Check',
  wire: 'Wire',
  other: 'Other',
};

const PAYMENT_METHOD_OPTIONS: Array<{ value: string; label: string }> = [
  { value: 'bank_transfer', label: 'Bank transfer' },
  { value: 'credit_card', label: 'Credit card' },
  { value: 'cash', label: 'Cash' },
  { value: 'cheque', label: 'Cheque' },
  { value: 'wire', label: 'Wire' },
  { value: 'other', label: 'Other' },
];

function formatPaymentMethod(method: string | null | undefined): string {
  if (!method) return '-';
  return PAYMENT_METHOD_LABELS[method] ?? method.replace(/_/g, ' ');
}

function formatDateOnly(value: string | null | undefined): string {
  if (!value) return '-';
  // Stored values are typically YYYY-MM-DD or ISO. Treat as date-only to avoid TZ shift.
  const isoDate = value.length === 10 ? value + 'T00:00:00' : value;
  const d = new Date(isoDate);
  if (Number.isNaN(d.getTime())) return value;
  return format(d, 'MMM d, yyyy');
}

interface InvoiceDetailProps {
  invoiceId: string;
}

interface InvoiceLineItem {
  id: string;
  description: string;
  quantity: number | string;
  unitPrice: number | string;
  total: number | string;
}

interface InvoiceLinkedExpense {
  id: string;
  establishmentName: string | null;
  category: string | null;
  expenseDate: string;
  amount: number | string;
  currency: string;
}

interface InvoiceDetailData {
  id: string;
  invoiceNumber: string;
  status: string;
  clientName: string;
  currency: string;
  total: number | string;
  subtotal: number | string;
  discountAmount: number | string;
  discountPct: number | string;
  feeAmount: number | string;
  feePct: number | string;
  dueDate: string | null;
  paymentTerms: string | null;
  notes: string | null;
  pdfFileId: string | null;
  paymentDate: string | null;
  paymentMethod: string | null;
  paymentReference: string | null;
  lineItems?: InvoiceLineItem[];
  linkedExpenses?: InvoiceLinkedExpense[];
}

export function InvoiceDetail({ invoiceId }: InvoiceDetailProps) {
  const queryClient = useQueryClient();
  const [tab, setTab] = useState('overview');

  const { data, isLoading, error } = useQuery<{ data: InvoiceDetailData }>({
    queryKey: ['invoices', invoiceId],
    queryFn: () => apiFetch<{ data: InvoiceDetailData }>(`/api/v1/invoices/${invoiceId}`),
  });

  const { setChrome } = useMobileChrome();
  const titleForChrome: string | null = data?.data?.invoiceNumber ?? null;
  useEffect(() => {
    setChrome({ title: titleForChrome, showBackButton: true });
    return () => setChrome({ title: null, showBackButton: false });
  }, [titleForChrome, setChrome]);

  const sendMutation = useMutation({
    mutationFn: () => apiFetch(`/api/v1/invoices/${invoiceId}/send`, { method: 'POST' }),
    onSuccess: () => {
      toast.success('Invoice sent');
      queryClient.invalidateQueries({ queryKey: ['invoices', invoiceId] });
      queryClient.invalidateQueries({ queryKey: ['invoices'] });
    },
    onError: (e) => toastError(e),
  });

  const paymentForm = useForm<RecordPaymentInput>({
    resolver: zodResolver(recordPaymentSchema),
    defaultValues: { paymentDate: new Date().toISOString().split('T')[0] },
  });
  const submitPaymentWithScroll = useFormScrollToError(
    paymentForm.handleSubmit,
    paymentForm.formState.errors,
  );

  const paymentMutation = useMutation({
    mutationFn: (values: RecordPaymentInput) =>
      apiFetch(`/api/v1/invoices/${invoiceId}/payment`, {
        method: 'PATCH',
        body: values,
      }),
    onSuccess: () => {
      toast.success('Payment recorded');
      queryClient.invalidateQueries({ queryKey: ['invoices', invoiceId] });
      queryClient.invalidateQueries({ queryKey: ['invoices'] });
    },
    onError: (e) => toastError(e),
  });

  if (isLoading) {
    return (
      <div className="flex items-center justify-center p-12">
        <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
      </div>
    );
  }

  if (error || !data?.data) {
    return (
      <div className="p-6 text-center text-muted-foreground">Failed to load invoice details.</div>
    );
  }

  const invoice = data.data;
  const statusColor = STATUS_COLORS[invoice.status] ?? STATUS_COLORS.draft;

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="rounded-xl border border-slate-200 bg-gradient-brand-soft px-5 py-4 shadow-xs flex items-center justify-between gap-4 flex-wrap">
        <div className="min-w-0">
          <div className="text-xs font-semibold uppercase tracking-wide text-brand">Invoice</div>
          <div className="mt-1 flex items-center gap-3 flex-wrap">
            <h1 className="truncate text-2xl font-bold tracking-tight text-foreground font-mono">
              {invoice.invoiceNumber}
            </h1>
            <Badge variant="outline" className={`capitalize text-sm border ${statusColor}`}>
              {invoice.status}
            </Badge>
          </div>
          <p className="text-sm text-muted-foreground mt-1">{invoice.clientName}</p>
        </div>
        <div className="flex items-center gap-2">
          {invoice.status === 'draft' && (
            <PermissionGate resource="invoices" action="send">
              <Button
                variant="outline"
                size="sm"
                onClick={() => sendMutation.mutate()}
                disabled={sendMutation.isPending}
              >
                {sendMutation.isPending ? (
                  <Loader2 className="mr-1.5 h-4 w-4 animate-spin" />
                ) : (
                  <Send className="mr-1.5 h-4 w-4" />
                )}
                Send Invoice
              </Button>
            </PermissionGate>
          )}
        </div>
      </div>

      <Tabs value={tab} onValueChange={setTab}>
        <TabsList>
          <TabsTrigger value="overview">Overview</TabsTrigger>
          <TabsTrigger value="expenses">Linked Expenses</TabsTrigger>
          <TabsTrigger value="payment">Payment</TabsTrigger>
        </TabsList>

        {/* Overview */}
        <TabsContent value="overview" className="space-y-4 pt-4">
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <Card>
              <CardHeader>
                <CardTitle className="text-sm font-medium">Total</CardTitle>
              </CardHeader>
              <CardContent>
                <p className="text-2xl font-bold tabular-nums">
                  {Number(invoice.total).toLocaleString(undefined, {
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 2,
                  })}{' '}
                  {invoice.currency}
                </p>
              </CardContent>
            </Card>
            <Card>
              <CardHeader>
                <CardTitle className="text-sm font-medium">Due Date</CardTitle>
              </CardHeader>
              <CardContent>
                <p className="text-sm">{formatDateOnly(invoice.dueDate)}</p>
              </CardContent>
            </Card>
            <Card>
              <CardHeader>
                <CardTitle className="text-sm font-medium">Payment Terms</CardTitle>
              </CardHeader>
              <CardContent>
                <p className="text-sm capitalize">{invoice.paymentTerms}</p>
              </CardContent>
            </Card>
          </div>

          {/* Line items */}
          {invoice.lineItems && invoice.lineItems.length > 0 && (
            <Card>
              <CardHeader>
                <CardTitle className="text-sm font-medium">Line Items</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-2">
                  <div className="grid grid-cols-12 gap-2 text-xs font-medium text-muted-foreground border-b pb-2">
                    <span className="col-span-6">Description</span>
                    <span className="col-span-2 text-right">Qty</span>
                    <span className="col-span-2 text-right">Unit Price</span>
                    <span className="col-span-2 text-right">Total</span>
                  </div>
                  {invoice.lineItems.map((li) => (
                    <div key={li.id} className="grid grid-cols-12 gap-2 text-sm">
                      <span className="col-span-6">{li.description}</span>
                      <span className="col-span-2 text-right tabular-nums">{li.quantity}</span>
                      <span className="col-span-2 text-right tabular-nums">
                        {Number(li.unitPrice).toFixed(2)}
                      </span>
                      <span className="col-span-2 text-right tabular-nums font-medium">
                        {Number(li.total).toFixed(2)}
                      </span>
                    </div>
                  ))}
                </div>

                {/* Totals */}
                <div className="mt-4 border-t pt-4 space-y-1 text-sm">
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">Subtotal</span>
                    <span className="tabular-nums">
                      {Number(invoice.subtotal).toFixed(2)} {invoice.currency}
                    </span>
                  </div>
                  {Number(invoice.discountAmount) > 0 && (
                    <div className="flex justify-between text-green-600">
                      <span>Discount ({invoice.discountPct}%)</span>
                      <span className="tabular-nums">
                        -{Number(invoice.discountAmount).toFixed(2)} {invoice.currency}
                      </span>
                    </div>
                  )}
                  {Number(invoice.feeAmount) > 0 && (
                    <div className="flex justify-between">
                      <span className="text-muted-foreground">Fee ({invoice.feePct}%)</span>
                      <span className="tabular-nums">
                        +{Number(invoice.feeAmount).toFixed(2)} {invoice.currency}
                      </span>
                    </div>
                  )}
                  <div className="flex justify-between font-semibold border-t pt-2">
                    <span>Total</span>
                    <span className="tabular-nums">
                      {Number(invoice.total).toFixed(2)} {invoice.currency}
                    </span>
                  </div>
                </div>
              </CardContent>
            </Card>
          )}

          {invoice.notes && (
            <Card>
              <CardHeader>
                <CardTitle className="text-sm font-medium">Notes</CardTitle>
              </CardHeader>
              <CardContent>
                <p className="text-sm text-muted-foreground whitespace-pre-wrap">{invoice.notes}</p>
              </CardContent>
            </Card>
          )}
        </TabsContent>

        {/* Linked Expenses */}
        <TabsContent value="expenses" className="pt-4">
          {invoice.linkedExpenses && invoice.linkedExpenses.length > 0 ? (
            <div className="space-y-2">
              {invoice.linkedExpenses.map((exp) => (
                <div
                  key={exp.id}
                  className="flex items-center justify-between p-3 border rounded-md text-sm"
                >
                  <div>
                    <p className="font-medium">{exp.establishmentName ?? 'Unnamed Expense'}</p>
                    <p className="text-muted-foreground text-xs">
                      {exp.category ?? '-'} &middot; {exp.expenseDate}
                    </p>
                  </div>
                  <span className="font-medium tabular-nums">
                    {Number(exp.amount).toFixed(2)} {exp.currency}
                  </span>
                </div>
              ))}
            </div>
          ) : (
            <p className="text-sm text-muted-foreground py-6 text-center">
              No expenses linked to this invoice.
            </p>
          )}
        </TabsContent>

        {/* Payment */}
        <TabsContent value="payment" className="pt-4">
          {invoice.status === 'paid' ? (
            <Card>
              <CardContent className="pt-6 space-y-3 text-sm">
                <div className="flex items-center gap-2">
                  <Badge variant="outline" className="bg-green-100 text-green-700 border-green-200">
                    Paid
                  </Badge>
                </div>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <span className="text-muted-foreground">Payment Date</span>
                    <p className="mt-0.5">{formatDateOnly(invoice.paymentDate)}</p>
                  </div>
                  <div>
                    <span className="text-muted-foreground">Method</span>
                    <p className="mt-0.5">{formatPaymentMethod(invoice.paymentMethod)}</p>
                  </div>
                  <div>
                    <span className="text-muted-foreground">Reference</span>
                    <p className="mt-0.5">{invoice.paymentReference ?? '-'}</p>
                  </div>
                </div>
              </CardContent>
            </Card>
          ) : (
            <PermissionGate resource="invoices" action="record_payment">
              <Card>
                <CardHeader>
                  <CardTitle className="text-sm font-medium">Record Payment</CardTitle>
                </CardHeader>
                <CardContent>
                  <form
                    onSubmit={submitPaymentWithScroll((values) => paymentMutation.mutate(values))}
                    className="space-y-4"
                  >
                    <FormErrorSummary
                      errors={paymentForm.formState.errors}
                      labels={{ paymentDate: 'Payment date', paymentMethod: 'Payment method' }}
                    />
                    <div className="space-y-1">
                      <Label htmlFor="paymentDate">Payment Date</Label>
                      <Controller
                        control={paymentForm.control}
                        name="paymentDate"
                        render={({ field }) => (
                          <DatePicker
                            id="paymentDate"
                            value={field.value ?? ''}
                            onChange={(v) => field.onChange(v || undefined)}
                          />
                        )}
                      />
                      {paymentForm.formState.errors.paymentDate && (
                        <p className="text-xs text-destructive">
                          {paymentForm.formState.errors.paymentDate.message}
                        </p>
                      )}
                    </div>
                    <div className="space-y-1">
                      <Label htmlFor="paymentMethod">Payment Method</Label>
                      <Select
                        value={paymentForm.watch('paymentMethod') ?? ''}
                        onValueChange={(v) =>
                          paymentForm.setValue('paymentMethod', v, { shouldValidate: true })
                        }
                      >
                        <SelectTrigger id="paymentMethod">
                          <SelectValue placeholder="Select a method" />
                        </SelectTrigger>
                        <SelectContent>
                          {PAYMENT_METHOD_OPTIONS.map((opt) => (
                            <SelectItem key={opt.value} value={opt.value}>
                              {opt.label}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                    <div className="space-y-1">
                      <Label htmlFor="paymentReference">Reference / Transaction ID</Label>
                      <Input
                        id="paymentReference"
                        placeholder="Optional reference"
                        {...paymentForm.register('paymentReference')}
                      />
                    </div>
                    <Button type="submit" disabled={paymentMutation.isPending}>
                      {paymentMutation.isPending ? (
                        <Loader2 className="mr-1.5 h-4 w-4 animate-spin" />
                      ) : (
                        <CreditCard className="mr-1.5 h-4 w-4" />
                      )}
                      Mark as Paid
                    </Button>
                  </form>
                </CardContent>
              </Card>
            </PermissionGate>
          )}
        </TabsContent>
      </Tabs>
    </div>
  );
}
