'use client';

import React, { useEffect, useState, useCallback } from 'react';
import { Card, CardHeader, CardTitle, CardContent } from '@alga-psa/ui/components/Card';
import { Table } from '@alga-psa/ui/components/Table';
import { getClientClient } from '@alga-psa/client-portal/actions';
import { getClientContractLine, getClientInvoices } from '@alga-psa/client-portal/actions';
import { useTranslation } from '@alga-psa/ui/lib/i18n/client';
import LoadingIndicator from '@alga-psa/ui/components/LoadingIndicator';

import type { IClient } from '@alga-psa/types';
import type { IClientContractLine } from '@alga-psa/types';
import type { InvoiceViewModel } from '@alga-psa/types';

export default function ClientAccount() {
  const { t: tProfile } = useTranslation('client-portal');
  const { t: tCommon } = useTranslation('common');
  const { t: tBilling } = useTranslation('features/billing');
  const [isLoading, setIsLoading] = useState(true);
  const [client, setClient] = useState<IClient | null>(null);
  const [contractLine, setContractLine] = useState<IClientContractLine | null>(null);
  const [invoices, setInvoices] = useState<InvoiceViewModel[]>([]);
  const [hasInvoiceAccess, setHasInvoiceAccess] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // Note: Invoice amounts are stored in cents, so we divide by 100
  const formatCurrency = useCallback((amountInCents: number | string | null | undefined, currencyCode: string = 'USD') => {
    try {
      const n = typeof amountInCents === 'string' ? Number(amountInCents) : (amountInCents ?? 0);
      return new Intl.NumberFormat('en-US', {
        style: 'currency',
        currency: currencyCode,
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      }).format((n as number) / 100);
    } catch {
      return new Intl.NumberFormat('en-US', {
        style: 'currency',
        currency: 'USD',
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      }).format(0);
    }
  }, []);

  const formatDate = useCallback((date: any) => {
    if (!date) return 'N/A';
    try {
      const d = new Date(typeof date === 'string' ? date : date.toString());
      return d.toLocaleDateString();
    } catch {
      return 'N/A';
    }
  }, []);

  useEffect(() => {
    let mounted = true;
    const load = async () => {
      try {
        const [clientData, plan] = await Promise.all([
          getClientClient(),
          getClientContractLine(),
        ]);

        if (!mounted) return;
        setClient(clientData);
        setContractLine(plan);

        try {
          const inv = await getClientInvoices();
          if (!mounted) return;
          setInvoices(inv);
          setHasInvoiceAccess(true);
        } catch (e) {
          if (!mounted) return;
          setHasInvoiceAccess(false);
        }
      } catch (e) {
        if (!mounted) return;
        setError(tProfile('clientSettings.messages.failedToLoad'));
      } finally {
        if (mounted) setIsLoading(false);
      }
    };
    load();
    return () => { mounted = false; };
  }, []);

  // const onCancelSubscription = () => {
  //   toast('Cancel subscription is not implemented yet.');
  // };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-8">
        <LoadingIndicator 
          layout="stacked" 
          text={tCommon('common.loading')}
          spinnerProps={{ size: 'md' }}
        />
      </div>
    );
  }

  if (error) {
    return (
      <Card className="p-6">
        <div className="text-red-600">{error}</div>
      </Card>
    );
  }

  return (
    <div className="space-y-8">
      {/* Client Details */}
      <Card id="client-details-card" className="bg-white">
        <CardHeader>
          <CardTitle>{tProfile('clientSettings.tabs.clientDetails')}</CardTitle>
        </CardHeader>
        <CardContent>
          {client ? (
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <div className="text-sm text-gray-600">{tProfile('clientSettings.fields.clientName')}</div>
                <div className="text-base font-medium">{client.client_name}</div>
              </div>
              <div>
                <div className="text-sm text-gray-600">{tProfile('clientSettings.fields.website')}</div>
                <div className="text-base font-medium">{client.properties?.website || client.url || '—'}</div>
              </div>
            </div>
          ) : (
            <div>{tCommon('common.noData')}</div>
          )}
        </CardContent>
      </Card>

      {/* Contract Line */}
      <Card id="contract-line-card" className="bg-white">
        <CardHeader>
          <CardTitle>{tBilling('currentContractLine')}</CardTitle>
        </CardHeader>
        <CardContent>
          {contractLine ? (
            <div className="flex items-center justify-between">
              <div className="space-y-1">
                <div className="text-base font-medium">{contractLine.contract_line_name}</div>
                <div className="text-sm text-gray-600">{contractLine.billing_frequency || '—'}</div>
              </div>
              {/* <div className="flex items-center gap-2">
                <Button id="cancel-subscription-button" variant="outline" onClick={onCancelSubscription}>
                  Cancel Subscription
                </Button>
              </div> */}
            </div>
          ) : (
            <div className="text-gray-600">{tCommon('common.noData')}</div>
          )}
        </CardContent>
      </Card>

      {/* Invoices */}
      <Card className="bg-white">
        <CardHeader>
          <CardTitle>{tBilling('tabs.invoices')}</CardTitle>
        </CardHeader>
        <CardContent>
          {!hasInvoiceAccess ? (
            <div className="text-sm text-gray-600">{tBilling('messages.noInvoices')}</div>
          ) : (
            <Table id="invoices-table">
              <thead>
                <tr>
                  <th>{tBilling('invoice.number')}</th>
                  <th>{tBilling('invoice.date')}</th>
                  <th>{tBilling('invoice.amount')}</th>
                  <th>{tBilling('invoice.status')}</th>
                </tr>
              </thead>
              <tbody>
                {invoices.length === 0 ? (
                  <tr>
                    <td colSpan={4} className="text-center py-4 text-gray-500">{tBilling('messages.noInvoices')}</td>
                  </tr>
                ) : (
                  invoices.slice(0, 10).map((inv) => (
                    <tr key={inv.invoice_id}>
                      <td>{inv.invoice_number}</td>
                      <td>{formatDate(inv.invoice_date)}</td>
                      <td>{formatCurrency(inv.total_amount ?? inv.total, inv.currencyCode)}</td>
                      <td>{inv.status}</td>
                    </tr>
                  ))
                )}
              </tbody>
            </Table>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
