'use client';

import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Download, Eye, Plus } from 'lucide-react';
import DataTable from '@/components/ui/DataTable';
import Badge from '@/components/ui/Badge';
import ActionButton from '@/components/ui/ActionButton';
import Modal from '@/components/ui/Modal';
import { reportsApi } from '@/lib/api';
import { formatDateTime, formatCurrency } from '@/lib/utils';

export default function OperationalReportsPage() {
  const [filters, setFilters] = useState({ search: '', reportType: '' });
  const [selectedReport, setSelectedReport] = useState<any>(null);
  const [showDetailsModal, setShowDetailsModal] = useState(false);
  const [showGenerateModal, setShowGenerateModal] = useState(false);
  const [generateForm, setGenerateForm] = useState({
    reportType: 'REVENUE',
    dateFrom: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
    dateTo: new Date().toISOString().split('T')[0],
  });

  const { data, isLoading, refetch } = useQuery({
    queryKey: ['operational-reports', filters],
    queryFn: () => reportsApi.listReports(filters.reportType || undefined),
  });

  const handleGenerateReport = async () => {
    try {
      await reportsApi.generateReport(generateForm);
      refetch();
      setShowGenerateModal(false);
    } catch (error) {
      console.error('Error generating report:', error);
    }
  };

  const getReportTypeBadgeColor = (type: string) => {
    switch (type) {
      case 'REVENUE':
        return 'success';
      case 'OCCUPANCY':
        return 'primary';
      case 'PERFORMANCE':
        return 'info';
      case 'AGENT_SALES':
        return 'secondary';
      default:
        return 'secondary';
    }
  };

  const formatReportType = (type: string) => {
    const typeMap: { [key: string]: string } = {
      REVENUE: 'Revenue Report',
      OCCUPANCY: 'Occupancy Report',
      PERFORMANCE: 'Performance Report',
      AGENT_SALES: 'Agent Sales Report',
      CANCELLATIONS: 'Cancellations Report',
      PAYMENT_METHODS: 'Payment Methods Report',
    };
    return typeMap[type] || type;
  };

  const columns = [
    {
      key: 'reportType',
      label: 'Report Type',
      sortable: true,
      render: (report: any) => (
        <Badge className={getReportTypeBadgeColor(report.reportType)}>
          {formatReportType(report.reportType)}
        </Badge>
      ),
    },
    {
      key: 'dateFrom',
      label: 'Period From',
      sortable: true,
      render: (report: any) => (
        <span className="text-sm">{new Date(report.dateFrom).toLocaleDateString()}</span>
      ),
    },
    {
      key: 'dateTo',
      label: 'Period To',
      sortable: true,
      render: (report: any) => (
        <span className="text-sm">{new Date(report.dateTo).toLocaleDateString()}</span>
      ),
    },
    {
      key: 'data',
      label: 'Summary',
      render: (report: any) => {
        const data = report.data || {};
        if (report.reportType === 'REVENUE') {
          return (
            <div className="text-sm">
              <p className="font-medium">{formatCurrency(data.totalRevenueMinor || 0, 'ETB')}</p>
              <p className="text-xs text-muted-foreground">{data.totalBookings || 0} bookings</p>
            </div>
          );
        }
        if (report.reportType === 'OCCUPANCY') {
          return (
            <div className="text-sm">
              <p className="font-medium">{(data.averageOccupancyRate || 0).toFixed(1)}% occupancy</p>
              <p className="text-xs text-muted-foreground">{data.totalSchedules || 0} schedules</p>
            </div>
          );
        }
        if (report.reportType === 'AGENT_SALES') {
          return (
            <div className="text-sm">
              <p className="font-medium">{data.totalAgentBookings || 0} bookings</p>
              <p className="text-xs text-muted-foreground">{Object.keys(data.byAgent || {}).length} agents</p>
            </div>
          );
        }
        if (report.reportType === 'CANCELLATIONS') {
          return (
            <div className="text-sm">
              <p className="font-medium">{data.totalCancellations || 0} cancellations</p>
              <p className="text-xs text-muted-foreground">Refunded: {formatCurrency(data.totalRefundedMinor || 0, 'ETB')}</p>
            </div>
          );
        }
        if (report.reportType === 'PAYMENT_METHODS') {
          return (
            <div className="text-sm">
              <p className="font-medium">{data.totalPayments || 0} payments</p>
              <p className="text-xs text-muted-foreground">{Object.keys(data.byMethod || {}).length} methods</p>
            </div>
          );
        }
        return <span className="text-sm text-muted-foreground">View details</span>;
      },
    },
    {
      key: 'createdAt',
      label: 'Generated',
      sortable: true,
      render: (report: any) => (
        <span className="text-sm">{formatDateTime(report.createdAt)}</span>
      ),
    },
  ];

  const actions = [
    {
      label: 'View Details',
      onClick: (report: any) => {
        setSelectedReport(report);
        setShowDetailsModal(true);
      },
      variant: 'secondary' as const,
      icon: Eye,
    },
  ];

  const reports = data?.items || data || [];

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-foreground">Operational Reports</h1>
          <p className="text-muted-foreground mt-1">View and analyze operational performance</p>
        </div>
        <div className="flex gap-2">
          <ActionButton icon={Plus} variant="primary" onClick={() => setShowGenerateModal(true)}>
            Generate Report
          </ActionButton>
          <ActionButton icon={Download} variant="secondary">
            Export All
          </ActionButton>
        </div>
      </div>

      {/* Filters */}
      <div className="card">
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div>
            <label className="label">Search (Report ID/Type)</label>
            <input
              type="text"
              placeholder="Search reports..."
              className="input"
              value={filters.search}
              onChange={(e) => setFilters({ ...filters, search: e.target.value })}
            />
          </div>
          <div>
            <label className="label">Report Type</label>
            <select
              className="input"
              value={filters.reportType}
              onChange={(e) => setFilters({ ...filters, reportType: e.target.value })}
            >
              <option value="">All Types</option>
              <option value="REVENUE">Revenue Report</option>
              <option value="OCCUPANCY">Occupancy Report</option>
              <option value="AGENT_SALES">Agent Sales Report</option>
              <option value="CANCELLATIONS">Cancellations Report</option>
              <option value="PAYMENT_METHODS">Payment Methods Report</option>
            </select>
          </div>
          <div className="flex items-end">
            <ActionButton
              variant="secondary"
              onClick={() => setFilters({ search: '', reportType: '' })}
              className="w-full"
            >
              Clear Filters
            </ActionButton>
          </div>
        </div>
      </div>

      {/* Reports Table */}
      <DataTable
        data={reports}
        columns={columns}
        actions={actions}
        loading={isLoading}
        emptyMessage="No operational reports found"
      />

      {/* Generate Report Modal */}
      <Modal
        isOpen={showGenerateModal}
        onClose={() => setShowGenerateModal(false)}
        title="Generate Report"
        size="sm"
      >
        <div className="space-y-4">
          <div>
            <label className="label">Report Type</label>
            <select
              className="input"
              value={generateForm.reportType}
              onChange={(e) => setGenerateForm({ ...generateForm, reportType: e.target.value })}
            >
              <option value="REVENUE">Revenue Report</option>
              <option value="OCCUPANCY">Occupancy Report</option>
              <option value="AGENT_SALES">Agent Sales Report</option>
              <option value="CANCELLATIONS">Cancellations Report</option>
              <option value="PAYMENT_METHODS">Payment Methods Report</option>
            </select>
          </div>
          <div>
            <label className="label">Date From</label>
            <input
              type="date"
              className="input"
              value={generateForm.dateFrom}
              onChange={(e) => setGenerateForm({ ...generateForm, dateFrom: e.target.value })}
            />
          </div>
          <div>
            <label className="label">Date To</label>
            <input
              type="date"
              className="input"
              value={generateForm.dateTo}
              onChange={(e) => setGenerateForm({ ...generateForm, dateTo: e.target.value })}
            />
          </div>
          <div className="flex gap-2 pt-4">
            <ActionButton
              variant="primary"
              onClick={handleGenerateReport}
              className="flex-1"
            >
              Generate
            </ActionButton>
            <ActionButton
              variant="secondary"
              onClick={() => setShowGenerateModal(false)}
              className="flex-1"
            >
              Cancel
            </ActionButton>
          </div>
        </div>
      </Modal>

      {/* Details Modal */}
      <Modal
        isOpen={showDetailsModal}
        onClose={() => {
          setShowDetailsModal(false);
          setSelectedReport(null);
        }}
        title={formatReportType(selectedReport?.reportType)}
        size="lg"
      >
        <div className="space-y-4">
          {/* Report Header */}
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="text-xs font-semibold text-muted-foreground">Report Type</label>
              <p className="text-sm mt-1 font-medium">{formatReportType(selectedReport?.reportType)}</p>
            </div>
            <div>
              <label className="text-xs font-semibold text-muted-foreground">Generated</label>
              <p className="text-sm mt-1">{formatDateTime(selectedReport?.createdAt)}</p>
            </div>
            <div>
              <label className="text-xs font-semibold text-muted-foreground">Period From</label>
              <p className="text-sm mt-1">{new Date(selectedReport?.dateFrom).toLocaleDateString()}</p>
            </div>
            <div>
              <label className="text-xs font-semibold text-muted-foreground">Period To</label>
              <p className="text-sm mt-1">{new Date(selectedReport?.dateTo).toLocaleDateString()}</p>
            </div>
          </div>

          {/* Revenue Report Data */}
          {selectedReport?.reportType === 'REVENUE' && (
            <div className="border-t pt-4">
              <h4 className="text-sm font-semibold mb-3">Revenue Metrics</h4>
              <div className="grid grid-cols-2 gap-4">
                <div className="bg-blue-50 dark:bg-blue-950/20 rounded-lg p-3">
                  <p className="text-xs text-muted-foreground">Total Revenue</p>
                  <p className="text-lg font-bold mt-1">
                    {formatCurrency(selectedReport?.data?.totalRevenueMinor || 0, 'ETB')}
                  </p>
                </div>
                <div className="bg-green-50 dark:bg-green-950/20 rounded-lg p-3">
                  <p className="text-xs text-muted-foreground">Total Bookings</p>
                  <p className="text-lg font-bold mt-1">
                    {(selectedReport?.data?.totalBookings || 0).toLocaleString()}
                  </p>
                </div>
              </div>
              {selectedReport?.data?.byPaymentMethod && (
                <div className="mt-4">
                  <p className="text-xs font-semibold mb-2 text-muted-foreground">By Payment Method</p>
                  <div className="space-y-2">
                    {Object.entries(selectedReport.data.byPaymentMethod).map(([method, amount]: [string, any]) => (
                      <div key={method} className="flex justify-between text-sm">
                        <span className="text-muted-foreground capitalize">{method.toLowerCase().replace('_', ' ')}</span>
                        <span className="font-medium">{formatCurrency(amount, 'ETB')}</span>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </div>
          )}

          {/* Occupancy Report Data */}
          {selectedReport?.reportType === 'OCCUPANCY' && (
            <div className="border-t pt-4">
              <h4 className="text-sm font-semibold mb-3">Occupancy Metrics</h4>
              <div className="grid grid-cols-2 gap-4">
                <div className="bg-blue-50 dark:bg-blue-950/20 rounded-lg p-3">
                  <p className="text-xs text-muted-foreground">Avg Occupancy Rate</p>
                  <p className="text-lg font-bold mt-1">
                    {(selectedReport?.data?.averageOccupancyRate || 0).toFixed(1)}%
                  </p>
                </div>
                <div className="bg-green-50 dark:bg-green-950/20 rounded-lg p-3">
                  <p className="text-xs text-muted-foreground">Total Schedules</p>
                  <p className="text-lg font-bold mt-1">
                    {(selectedReport?.data?.totalSchedules || 0).toLocaleString()}
                  </p>
                </div>
              </div>
            </div>
          )}

          {/* Agent Sales Report Data */}
          {selectedReport?.reportType === 'AGENT_SALES' && (
            <div className="border-t pt-4">
              <h4 className="text-sm font-semibold mb-3">Agent Sales Metrics</h4>
              <div className="grid grid-cols-2 gap-4">
                <div className="bg-blue-50 dark:bg-blue-950/20 rounded-lg p-3">
                  <p className="text-xs text-muted-foreground">Total Bookings</p>
                  <p className="text-lg font-bold mt-1">
                    {(selectedReport?.data?.totalAgentBookings || 0).toLocaleString()}
                  </p>
                </div>
                <div className="bg-green-50 dark:bg-green-950/20 rounded-lg p-3">
                  <p className="text-xs text-muted-foreground">Active Agents</p>
                  <p className="text-lg font-bold mt-1">
                    {Object.keys(selectedReport?.data?.byAgent || {}).length}
                  </p>
                </div>
              </div>
              {selectedReport?.data?.byAgent && (
                <div className="mt-4">
                  <p className="text-xs font-semibold mb-2 text-muted-foreground">By Agent</p>
                  <div className="space-y-2 max-h-64 overflow-y-auto">
                    {Object.entries(selectedReport.data.byAgent).map(([agent, stats]: [string, any]) => (
                      <div key={agent} className="text-sm border-b pb-2 last:border-0">
                        <p className="font-medium">{agent}</p>
                        <div className="text-xs text-muted-foreground mt-1">
                          <p>Bookings: {stats.bookings} | Revenue: {formatCurrency(stats.revenueMinor, 'ETB')}</p>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </div>
          )}

          {/* Cancellations Report Data */}
          {selectedReport?.reportType === 'CANCELLATIONS' && (
            <div className="border-t pt-4">
              <h4 className="text-sm font-semibold mb-3">Cancellation Metrics</h4>
              <div className="grid grid-cols-2 gap-4">
                <div className="bg-blue-50 dark:bg-blue-950/20 rounded-lg p-3">
                  <p className="text-xs text-muted-foreground">Total Cancellations</p>
                  <p className="text-lg font-bold mt-1">
                    {(selectedReport?.data?.totalCancellations || 0).toLocaleString()}
                  </p>
                </div>
                <div className="bg-green-50 dark:bg-green-950/20 rounded-lg p-3">
                  <p className="text-xs text-muted-foreground">Total Refunded</p>
                  <p className="text-lg font-bold mt-1">
                    {formatCurrency(selectedReport?.data?.totalRefundedMinor || 0, 'ETB')}
                  </p>
                </div>
              </div>
            </div>
          )}

          {/* Payment Methods Report Data */}
          {selectedReport?.reportType === 'PAYMENT_METHODS' && (
            <div className="border-t pt-4">
              <h4 className="text-sm font-semibold mb-3">Payment Method Breakdown</h4>
              <div className="bg-blue-50 dark:bg-blue-950/20 rounded-lg p-3 mb-4">
                <p className="text-xs text-muted-foreground">Total Payments</p>
                <p className="text-lg font-bold mt-1">
                  {(selectedReport?.data?.totalPayments || 0).toLocaleString()}
                </p>
              </div>
              {selectedReport?.data?.byMethod && (
                <div className="space-y-2">
                  {Object.entries(selectedReport.data.byMethod).map(([method, stats]: [string, any]) => (
                    <div key={method} className="flex justify-between items-center p-3 bg-gray-50 dark:bg-gray-900 rounded">
                      <div>
                        <p className="text-sm font-medium capitalize">{method.toLowerCase().replace('_', ' ')}</p>
                        <p className="text-xs text-muted-foreground">{stats.count} transactions</p>
                      </div>
                      <p className="font-bold">{formatCurrency(stats.totalMinor, 'ETB')}</p>
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}

          {/* Report ID */}
          <div className="border-t pt-4">
            <label className="text-xs font-semibold text-muted-foreground">Report ID</label>
            <p className="text-xs mt-1 font-mono text-muted-foreground break-all">{selectedReport?.id}</p>
          </div>
        </div>
      </Modal>
    </div>
  );
}
