import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { pdf } from '@react-pdf/renderer';
import { api } from '@/lib/api';
import { Loading } from '@/components/Loading';
import { AccountabilityRosterPDF } from '@/components/AccountabilityRosterPDF';
import { usePdfSettings } from '@/hooks/useSettings';
import toast from 'react-hot-toast';
import {
  FileText,
  Users,
  Phone,
  Mail,
  Building2,
  AlertTriangle,
  Search,
  Download,
  UserCheck,
  ClipboardList,
  Send,
  MessageCircle,
  X,
  Loader2,
} from 'lucide-react';

interface VIP {
  id: string;
  name: string;
  organization: string | null;
  department: string;
  phone: string | null;
  email: string | null;
  emergencyContactName: string | null;
  emergencyContactPhone: string | null;
  isRosterOnly: boolean;
  partySize: number;
  arrivalMode: string;
  notes: string | null;
}

type ReportType = 'accountability';

export function Reports() {
  const [activeReport, setActiveReport] = useState<ReportType>('accountability');
  const [searchTerm, setSearchTerm] = useState('');
  const [departmentFilter, setDepartmentFilter] = useState<string>('all');
  const [showSignalModal, setShowSignalModal] = useState(false);
  const [signalPhoneNumber, setSignalPhoneNumber] = useState('');
  const [signalMessage, setSignalMessage] = useState('');
  const [isSendingSignal, setIsSendingSignal] = useState(false);

  const { data: vips, isLoading } = useQuery<VIP[]>({
    queryKey: ['vips'],
    queryFn: async () => {
      const { data } = await api.get('/vips');
      return data;
    },
  });

  const { data: pdfSettings } = usePdfSettings();

  const reports = [
    {
      id: 'accountability' as const,
      name: 'Accountability Roster',
      icon: ClipboardList,
      description: 'Complete list of all personnel for emergency preparedness',
    },
  ];

  // Filter VIPs based on search and department
  const filteredVips = vips?.filter((vip) => {
    const matchesSearch =
      searchTerm === '' ||
      vip.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      vip.organization?.toLowerCase().includes(searchTerm.toLowerCase()) ||
      vip.email?.toLowerCase().includes(searchTerm.toLowerCase());

    const matchesDepartment =
      departmentFilter === 'all' || vip.department === departmentFilter;

    return matchesSearch && matchesDepartment;
  });

  // Separate active VIPs and roster-only
  const activeVips = filteredVips?.filter((v) => !v.isRosterOnly) || [];
  const rosterOnlyVips = filteredVips?.filter((v) => v.isRosterOnly) || [];

  // Count totals (including party size)
  const totalPeople =
    (vips?.reduce((sum, v) => sum + (v.partySize || 1), 0) || 0);
  const activeCount = activeVips.reduce((sum, v) => sum + (v.partySize || 1), 0);
  const rosterOnlyCount = rosterOnlyVips.reduce((sum, v) => sum + (v.partySize || 1), 0);

  // Export to CSV
  const handleExportCSV = () => {
    if (!filteredVips) return;

    const headers = [
      'Name',
      'Organization',
      'Department',
      'Phone',
      'Email',
      'Emergency Contact',
      'Emergency Phone',
      'Party Size',
      'Status',
      'Notes',
    ];

    const rows = filteredVips.map((vip) => [
      vip.name,
      vip.organization || '',
      vip.department,
      vip.phone || '',
      vip.email || '',
      vip.emergencyContactName || '',
      vip.emergencyContactPhone || '',
      vip.partySize.toString(),
      vip.isRosterOnly ? 'Roster Only' : 'Active VIP',
      vip.notes?.replace(/\n/g, ' ') || '',
    ]);

    const csvContent = [
      headers.join(','),
      ...rows.map((row) =>
        row.map((cell) => `"${cell.replace(/"/g, '""')}"`).join(',')
      ),
    ].join('\n');

    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = `accountability-roster-${new Date().toISOString().split('T')[0]}.csv`;
    link.click();
  };

  // Export to PDF
  const handleExportPDF = async () => {
    if (!filteredVips) return;

    try {
      const blob = await pdf(
        <AccountabilityRosterPDF
          vips={filteredVips}
          settings={pdfSettings}
        />
      ).toBlob();

      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      const now = new Date();
      const timestamp = now.toLocaleDateString('en-US', { month: 'short', day: '2-digit' }).replace(' ', '') +
        '_' + now.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', hour12: false }).replace(':', '');
      link.download = `Accountability_Roster_${timestamp}.pdf`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);
      toast.success('PDF downloaded');
    } catch (error) {
      console.error('[PDF] Generation failed:', error);
      toast.error('Failed to generate PDF. Please try again.');
    }
  };

  // Send PDF via Signal
  const handleSendViaSignal = async () => {
    if (!filteredVips || !signalPhoneNumber.trim()) return;

    setIsSendingSignal(true);
    try {
      const pdfBlob = await pdf(
        <AccountabilityRosterPDF
          vips={filteredVips}
          settings={pdfSettings}
        />
      ).toBlob();

      // Convert blob to base64
      const reader = new FileReader();
      const base64Promise = new Promise<string>((resolve, reject) => {
        reader.onloadend = () => {
          const base64 = (reader.result as string).split(',')[1];
          resolve(base64);
        };
        reader.onerror = reject;
      });
      reader.readAsDataURL(pdfBlob);
      const base64Data = await base64Promise;

      const now = new Date();
      const timestamp = now.toLocaleDateString('en-US', { month: 'short', day: '2-digit' }).replace(' ', '') +
        '_' + now.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', hour12: false }).replace(':', '');
      const filename = `Accountability_Roster_${timestamp}.pdf`;

      const response = await api.post('/signal/send-attachment', {
        to: signalPhoneNumber,
        message: signalMessage || 'Accountability Roster attached',
        attachment: base64Data,
        filename,
        mimeType: 'application/pdf',
      });

      if (response.data.success) {
        toast.success('Roster sent via Signal!');
        setShowSignalModal(false);
        setSignalPhoneNumber('');
        setSignalMessage('');
      } else {
        toast.error(response.data.error || 'Failed to send via Signal');
      }
    } catch (error: any) {
      console.error('[Signal] Failed to send:', error);
      toast.error(error.response?.data?.message || 'Failed to send via Signal');
    } finally {
      setIsSendingSignal(false);
    }
  };

  if (isLoading) {
    return <Loading message="Loading report data..." />;
  }

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-3xl font-bold text-foreground">Reports</h1>
          <p className="text-muted-foreground mt-1">
            Generate and view operational reports
          </p>
        </div>
      </div>

      {/* Report Type Selector */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 mb-6">
        {reports.map((report) => {
          const Icon = report.icon;
          const isActive = activeReport === report.id;
          return (
            <button
              key={report.id}
              onClick={() => setActiveReport(report.id)}
              className={`p-4 rounded-lg border text-left transition-all ${
                isActive
                  ? 'border-primary bg-primary/5 ring-2 ring-primary/20'
                  : 'border-border bg-card hover:border-primary/50 hover:bg-accent'
              }`}
            >
              <div className="flex items-center gap-3">
                <div
                  className={`p-2 rounded-lg ${
                    isActive ? 'bg-primary/10 text-primary' : 'bg-muted text-muted-foreground'
                  }`}
                >
                  <Icon className="h-5 w-5" />
                </div>
                <div>
                  <div className="font-medium text-foreground">{report.name}</div>
                  <div className="text-sm text-muted-foreground">{report.description}</div>
                </div>
              </div>
            </button>
          );
        })}
      </div>

      {/* Accountability Report */}
      {activeReport === 'accountability' && (
        <div className="space-y-6">
          {/* Summary Stats */}
          <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
            <div className="bg-card border border-border rounded-lg p-4">
              <div className="flex items-center gap-3">
                <div className="p-2 bg-blue-100 dark:bg-blue-950 rounded-lg">
                  <Users className="h-5 w-5 text-blue-600 dark:text-blue-400" />
                </div>
                <div>
                  <div className="text-2xl font-bold text-foreground">{totalPeople}</div>
                  <div className="text-sm text-muted-foreground">Total People</div>
                </div>
              </div>
            </div>
            <div className="bg-card border border-border rounded-lg p-4">
              <div className="flex items-center gap-3">
                <div className="p-2 bg-green-100 dark:bg-green-950 rounded-lg">
                  <UserCheck className="h-5 w-5 text-green-600 dark:text-green-400" />
                </div>
                <div>
                  <div className="text-2xl font-bold text-foreground">{activeCount}</div>
                  <div className="text-sm text-muted-foreground">Active VIPs</div>
                </div>
              </div>
            </div>
            <div className="bg-card border border-border rounded-lg p-4">
              <div className="flex items-center gap-3">
                <div className="p-2 bg-amber-100 dark:bg-amber-950 rounded-lg">
                  <ClipboardList className="h-5 w-5 text-amber-600 dark:text-amber-400" />
                </div>
                <div>
                  <div className="text-2xl font-bold text-foreground">{rosterOnlyCount}</div>
                  <div className="text-sm text-muted-foreground">Roster Only</div>
                </div>
              </div>
            </div>
          </div>

          {/* Filters and Export */}
          <div className="flex flex-col sm:flex-row gap-4 items-start sm:items-center justify-between">
            <div className="flex flex-col sm:flex-row gap-3 flex-1">
              <div className="relative flex-1 max-w-md">
                <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                <input
                  type="text"
                  placeholder="Search by name, organization, or email..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="w-full pl-10 pr-4 py-2 border border-input rounded-lg bg-background focus:ring-2 focus:ring-primary focus:border-transparent"
                />
              </div>
              <select
                value={departmentFilter}
                onChange={(e) => setDepartmentFilter(e.target.value)}
                className="px-3 py-2 border border-input rounded-lg bg-background focus:ring-2 focus:ring-primary focus:border-transparent"
              >
                <option value="all">All Departments</option>
                <option value="OFFICE_OF_DEVELOPMENT">Office of Development</option>
                <option value="ADMIN">Admin</option>
                <option value="OTHER">Other</option>
              </select>
            </div>
            <div className="flex gap-2">
              <button
                onClick={handleExportCSV}
                className="inline-flex items-center gap-2 px-4 py-2 border border-input rounded-lg text-foreground hover:bg-accent transition-colors"
              >
                <Download className="h-4 w-4" />
                CSV
              </button>
              <button
                onClick={handleExportPDF}
                className="inline-flex items-center gap-2 px-4 py-2 bg-primary text-primary-foreground rounded-lg hover:bg-primary/90 transition-colors"
              >
                <FileText className="h-4 w-4" />
                PDF
              </button>
              <button
                onClick={() => setShowSignalModal(true)}
                className="inline-flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
              >
                <Send className="h-4 w-4" />
                Signal
              </button>
            </div>
          </div>

          {/* Active VIPs Table */}
          {activeVips.length > 0 && (
            <div>
              <h2 className="text-lg font-semibold text-foreground mb-3 flex items-center gap-2">
                <UserCheck className="h-5 w-5 text-green-600" />
                Active VIPs ({activeVips.length} entries, {activeCount} people)
              </h2>
              <div className="bg-card border border-border rounded-lg overflow-hidden">
                <div className="overflow-x-auto">
                  <table className="min-w-full divide-y divide-border">
                    <thead className="bg-muted/30">
                      <tr>
                        <th className="px-4 py-3 text-left text-xs font-medium text-muted-foreground uppercase">
                          Name
                        </th>
                        <th className="px-4 py-3 text-left text-xs font-medium text-muted-foreground uppercase">
                          Organization
                        </th>
                        <th className="px-4 py-3 text-left text-xs font-medium text-muted-foreground uppercase">
                          Contact
                        </th>
                        <th className="px-4 py-3 text-left text-xs font-medium text-muted-foreground uppercase">
                          Emergency Contact
                        </th>
                        <th className="px-4 py-3 text-center text-xs font-medium text-muted-foreground uppercase">
                          Party
                        </th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-border">
                      {activeVips.map((vip) => (
                        <tr key={vip.id} className="hover:bg-accent/50 transition-colors">
                          <td className="px-4 py-3">
                            <div className="font-medium text-foreground">{vip.name}</div>
                            <div className="text-xs text-muted-foreground">
                              {vip.department === 'OFFICE_OF_DEVELOPMENT'
                                ? 'Office of Development'
                                : vip.department}
                            </div>
                          </td>
                          <td className="px-4 py-3 text-sm text-muted-foreground">
                            {vip.organization && (
                              <div className="flex items-center gap-1">
                                <Building2 className="h-3 w-3" />
                                {vip.organization}
                              </div>
                            )}
                          </td>
                          <td className="px-4 py-3 text-sm">
                            {vip.phone && (
                              <div className="flex items-center gap-1 text-muted-foreground">
                                <Phone className="h-3 w-3" />
                                {vip.phone}
                              </div>
                            )}
                            {vip.email && (
                              <div className="flex items-center gap-1 text-muted-foreground">
                                <Mail className="h-3 w-3" />
                                {vip.email}
                              </div>
                            )}
                            {!vip.phone && !vip.email && (
                              <span className="text-muted-foreground/50 italic">No contact info</span>
                            )}
                          </td>
                          <td className="px-4 py-3 text-sm">
                            {vip.emergencyContactName ? (
                              <div>
                                <div className="flex items-center gap-1 text-foreground">
                                  <AlertTriangle className="h-3 w-3 text-amber-500" />
                                  {vip.emergencyContactName}
                                </div>
                                {vip.emergencyContactPhone && (
                                  <div className="text-muted-foreground text-xs">
                                    {vip.emergencyContactPhone}
                                  </div>
                                )}
                              </div>
                            ) : (
                              <span className="text-muted-foreground/50 italic">Not provided</span>
                            )}
                          </td>
                          <td className="px-4 py-3 text-center">
                            <span className="inline-flex items-center justify-center w-6 h-6 rounded-full bg-muted text-sm font-medium">
                              {vip.partySize}
                            </span>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          )}

          {/* Roster-Only Table */}
          {rosterOnlyVips.length > 0 && (
            <div>
              <h2 className="text-lg font-semibold text-foreground mb-3 flex items-center gap-2">
                <ClipboardList className="h-5 w-5 text-amber-600" />
                Roster Only ({rosterOnlyVips.length} entries, {rosterOnlyCount} people)
              </h2>
              <div className="bg-card border border-border rounded-lg overflow-hidden">
                <div className="overflow-x-auto">
                  <table className="min-w-full divide-y divide-border">
                    <thead className="bg-muted/30">
                      <tr>
                        <th className="px-4 py-3 text-left text-xs font-medium text-muted-foreground uppercase">
                          Name
                        </th>
                        <th className="px-4 py-3 text-left text-xs font-medium text-muted-foreground uppercase">
                          Organization
                        </th>
                        <th className="px-4 py-3 text-left text-xs font-medium text-muted-foreground uppercase">
                          Contact
                        </th>
                        <th className="px-4 py-3 text-left text-xs font-medium text-muted-foreground uppercase">
                          Emergency Contact
                        </th>
                        <th className="px-4 py-3 text-center text-xs font-medium text-muted-foreground uppercase">
                          Party
                        </th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-border">
                      {rosterOnlyVips.map((vip) => (
                        <tr key={vip.id} className="hover:bg-accent/50 transition-colors bg-amber-50/30 dark:bg-amber-950/10">
                          <td className="px-4 py-3">
                            <div className="font-medium text-foreground">{vip.name}</div>
                            <div className="text-xs text-muted-foreground">
                              {vip.department === 'OFFICE_OF_DEVELOPMENT'
                                ? 'Office of Development'
                                : vip.department}
                            </div>
                          </td>
                          <td className="px-4 py-3 text-sm text-muted-foreground">
                            {vip.organization && (
                              <div className="flex items-center gap-1">
                                <Building2 className="h-3 w-3" />
                                {vip.organization}
                              </div>
                            )}
                          </td>
                          <td className="px-4 py-3 text-sm">
                            {vip.phone && (
                              <div className="flex items-center gap-1 text-muted-foreground">
                                <Phone className="h-3 w-3" />
                                {vip.phone}
                              </div>
                            )}
                            {vip.email && (
                              <div className="flex items-center gap-1 text-muted-foreground">
                                <Mail className="h-3 w-3" />
                                {vip.email}
                              </div>
                            )}
                            {!vip.phone && !vip.email && (
                              <span className="text-muted-foreground/50 italic">No contact info</span>
                            )}
                          </td>
                          <td className="px-4 py-3 text-sm">
                            {vip.emergencyContactName ? (
                              <div>
                                <div className="flex items-center gap-1 text-foreground">
                                  <AlertTriangle className="h-3 w-3 text-amber-500" />
                                  {vip.emergencyContactName}
                                </div>
                                {vip.emergencyContactPhone && (
                                  <div className="text-muted-foreground text-xs">
                                    {vip.emergencyContactPhone}
                                  </div>
                                )}
                              </div>
                            ) : (
                              <span className="text-muted-foreground/50 italic">Not provided</span>
                            )}
                          </td>
                          <td className="px-4 py-3 text-center">
                            <span className="inline-flex items-center justify-center w-6 h-6 rounded-full bg-muted text-sm font-medium">
                              {vip.partySize}
                            </span>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          )}

          {/* Empty State */}
          {filteredVips?.length === 0 && (
            <div className="text-center py-12 bg-card border border-border rounded-lg">
              <FileText className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
              <h3 className="text-lg font-medium text-foreground mb-2">No entries found</h3>
              <p className="text-muted-foreground">
                {searchTerm || departmentFilter !== 'all'
                  ? 'Try adjusting your search or filter criteria.'
                  : 'Add VIPs to the system to see them in this report.'}
              </p>
            </div>
          )}
        </div>
      )}

      {/* Signal Send Modal */}
      {showSignalModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-card rounded-lg shadow-xl max-w-md w-full border border-border">
            <div className="flex items-center justify-between p-4 border-b border-border">
              <h2 className="text-lg font-semibold text-foreground flex items-center gap-2">
                <MessageCircle className="h-5 w-5" />
                Send Roster via Signal
              </h2>
              <button
                onClick={() => {
                  setShowSignalModal(false);
                  setSignalPhoneNumber('');
                  setSignalMessage('');
                }}
                className="text-muted-foreground hover:text-foreground"
              >
                <X className="h-5 w-5" />
              </button>
            </div>

            <div className="p-4 space-y-4">
              <p className="text-sm text-muted-foreground">
                Send the Accountability Roster PDF directly to a phone via Signal.
              </p>

              <div>
                <label className="block text-sm font-medium text-foreground mb-1">
                  Phone Number *
                </label>
                <input
                  type="tel"
                  value={signalPhoneNumber}
                  onChange={(e) => setSignalPhoneNumber(e.target.value)}
                  placeholder="+1 (555) 123-4567"
                  className="w-full px-3 py-2 border border-input rounded-lg bg-background text-foreground placeholder:text-muted-foreground focus:ring-2 focus:ring-primary focus:border-transparent"
                />
                <p className="text-xs text-muted-foreground mt-1">
                  Include country code (e.g., +1 for US)
                </p>
              </div>

              <div>
                <label className="block text-sm font-medium text-foreground mb-1">
                  Message (optional)
                </label>
                <textarea
                  value={signalMessage}
                  onChange={(e) => setSignalMessage(e.target.value)}
                  placeholder="Accountability Roster attached"
                  rows={2}
                  className="w-full px-3 py-2 border border-input rounded-lg bg-background text-foreground placeholder:text-muted-foreground focus:ring-2 focus:ring-primary focus:border-transparent resize-none"
                />
              </div>

              <div className="bg-muted/50 p-3 rounded-lg">
                <p className="text-xs text-muted-foreground">
                  <strong>Attachment:</strong> Accountability_Roster_[timestamp].pdf
                </p>
              </div>
            </div>

            <div className="flex gap-3 p-4 border-t border-border">
              <button
                onClick={() => {
                  setShowSignalModal(false);
                  setSignalPhoneNumber('');
                  setSignalMessage('');
                }}
                className="flex-1 px-4 py-2 border border-input rounded-lg text-foreground hover:bg-accent transition-colors"
              >
                Cancel
              </button>
              <button
                onClick={handleSendViaSignal}
                disabled={!signalPhoneNumber.trim() || isSendingSignal}
                className="flex-1 px-4 py-2 bg-primary text-white rounded-lg font-medium hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed transition-colors flex items-center justify-center gap-2"
              >
                {isSendingSignal ? (
                  <>
                    <Loader2 className="h-4 w-4 animate-spin" />
                    Sending...
                  </>
                ) : (
                  <>
                    <Send className="h-4 w-4" />
                    Send PDF
                  </>
                )}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
