import React from 'react';

const OUTPUT_GROUPS: Record<string, { label: string; fields: { key: string; label: string }[] }> = {
  propertyInfo: {
    label: 'Property Info',
    fields: [
      { key: 'address', label: 'Address' },
      { key: 'type', label: 'Property Type' },
      { key: 'units', label: 'Units' },
      { key: 'sqft', label: 'Square Footage' },
      { key: 'yearBuilt', label: 'Year Built' },
      { key: 'lotSize', label: 'Lot Size' },
      { key: 'zoning', label: 'Zoning' },
      { key: 'opportunityZone', label: 'Opportunity Zone' },
      { key: 'apn', label: 'APN' },
      { key: 'legal', label: 'Legal Description' },
    ],
  },
  ownerInfo: {
    label: 'Owner Info',
    fields: [
      { key: 'name', label: 'Owner Name' },
      { key: 'company', label: 'Company' },
      { key: 'portfolioSize', label: 'Portfolio Size' },
      { key: 'portfolioValue', label: 'Portfolio Value' },
      { key: 'ownerType', label: 'Owner Type' },
    ],
  },
  contactInfo: {
    label: 'Contacts',
    fields: [
      { key: 'phones', label: 'Phone Numbers' },
      { key: 'emails', label: 'Email Addresses' },
    ],
  },
  salesInfo: {
    label: 'Sales History',
    fields: [
      { key: 'lastSaleDate', label: 'Last Sale Date' },
      { key: 'lastSalePrice', label: 'Last Sale Price' },
      { key: 'buyer', label: 'Buyer' },
      { key: 'seller', label: 'Seller' },
      { key: 'deedType', label: 'Deed Type' },
    ],
  },
  debtInfo: {
    label: 'Debt / Mortgage',
    fields: [
      { key: 'lender', label: 'Lender' },
      { key: 'loanType', label: 'Loan Type' },
      { key: 'mortgageAmount', label: 'Mortgage Amount' },
      { key: 'maturityDate', label: 'Maturity Date' },
      { key: 'interestType', label: 'Interest Type' },
    ],
  },
  taxInfo: {
    label: 'Tax Assessment',
    fields: [
      { key: 'assessedValue', label: 'Assessed Value' },
      { key: 'taxAmount', label: 'Tax Amount' },
    ],
  },
};

interface OutputFieldSelectorProps {
  selected: Record<string, string[]>;
  onChange: (selected: Record<string, string[]>) => void;
}

export function OutputFieldSelector({ selected, onChange }: OutputFieldSelectorProps) {
  const toggleGroup = (group: string) => {
    const fields = OUTPUT_GROUPS[group].fields.map((f) => f.key);
    const current = selected[group] || [];
    const allSelected = fields.every((f) => current.includes(f));
    onChange({
      ...selected,
      [group]: allSelected ? [] : fields,
    });
  };

  const toggleField = (group: string, field: string) => {
    const current = selected[group] || [];
    onChange({
      ...selected,
      [group]: current.includes(field)
        ? current.filter((f) => f !== field)
        : [...current, field],
    });
  };

  const totalSelected = Object.values(selected).reduce((sum, arr) => sum + arr.length, 0);

  return (
    <div className="space-y-3">
      <div className="flex items-center justify-between">
        <span className="text-xs text-gray-400">{totalSelected} fields selected</span>
      </div>
      {Object.entries(OUTPUT_GROUPS).map(([group, { label, fields }]) => {
        const groupSelected = selected[group] || [];
        const allChecked = fields.every((f) => groupSelected.includes(f.key));
        const someChecked = groupSelected.length > 0 && !allChecked;

        return (
          <div key={group} className="space-y-1">
            <button
              onClick={() => toggleGroup(group)}
              className="flex items-center gap-2 text-sm font-medium text-gray-200 hover:text-reo-teal transition-colors"
            >
              <span className={`w-3.5 h-3.5 rounded border flex items-center justify-center text-[10px] ${
                allChecked ? 'bg-reo-teal border-reo-teal text-white' :
                someChecked ? 'bg-reo-teal/30 border-reo-teal text-white' : 'border-gray-500'
              }`}>
                {allChecked ? '✓' : someChecked ? '–' : ''}
              </span>
              {label}
            </button>
            <div className="grid grid-cols-2 gap-x-2 gap-y-0.5 pl-6">
              {fields.map(({ key, label: fieldLabel }) => (
                <label
                  key={key}
                  className="flex items-center gap-1.5 text-sm text-gray-400 hover:text-gray-200 cursor-pointer"
                >
                  <input
                    type="checkbox"
                    checked={groupSelected.includes(key)}
                    onChange={() => toggleField(group, key)}
                    className="rounded border-gray-500 text-reo-teal focus:ring-reo-teal bg-transparent w-3 h-3"
                  />
                  <span className="truncate">{fieldLabel}</span>
                </label>
              ))}
            </div>
          </div>
        );
      })}
    </div>
  );
}
