'use client';

import { useState, useMemo } from 'react';
import { routes } from '@/config/routes';
import { useDrawer } from '@/components/common/Drawer';
import TableLayout from '../../table-layout';
import Select from "react-select";
import {
  PiPlusBold,
  PiExport,
  PiListBullets,
  PiStack,
  PiCompassRose,
  PiBuildings,
  PiChartBar,
  PiWarning,
  PiArrowsDownUp,
  PiCheckCircle,
  PiGridFour,
  PiFunnel,
  PiCompass,
  PiCaretDoubleDown,
  PiCaretDoubleLeft,
  PiCaretDoubleRight,
  PiUser,
  PiClock,
  PiLock,
} from 'react-icons/pi';
import PropertyDrawer from '@/components/drawer/manage_property/PropertyDrawer';
import ConfirmModal from '@/components/common/confirm-modal';
import DataTable from '@/components/common/DataTable';
import ViewToggle from '@/components/common/ViewToggle';
import UnitSpecDrawer from '@/components/drawer/manage_property/UnitSpecDrawer';

// ── Types ──────────────────────────────────────────────────────────────
type InventoryStatus = 'Available' | 'Booked' | 'Reserved' | 'Blocked';
type Facing = 'East' | 'West' | 'North' | 'South';
type ConstructionStage = 'Finishing' | 'Structure' | 'Foundation' | 'Handover';

interface Unit {
  id: number;
  unitNum: string;
  towerBlock: string;
  bhk: string;
  sqft: number;
  facing: Facing;
  status: InventoryStatus;
  constructionStage: ConstructionStage;
  qualityDefects: string;
  basePrice: number;
}


// ── Static data ────────────────────────────────────────────────────────
const INITIAL_UNITS: Unit[] = [
  { id: 1, unitNum: 'A-101', towerBlock: 'Wing A', bhk: '3BHK', sqft: 1800, facing: 'East', status: 'Available', constructionStage: 'Finishing', qualityDefects: 'No Issues', basePrice: 25000000 },
  { id: 2, unitNum: 'A-102', towerBlock: 'Wing A', bhk: '2BHK', sqft: 1200, facing: 'North', status: 'Booked', constructionStage: 'Finishing', qualityDefects: 'No Issues', basePrice: 18000000 },
  { id: 3, unitNum: 'A-201', towerBlock: 'Wing A', bhk: '3BHK', sqft: 1800, facing: 'East', status: 'Reserved', constructionStage: 'Structure', qualityDefects: 'No Issues', basePrice: 25500000 },
  { id: 4, unitNum: 'A-202', towerBlock: 'Wing A', bhk: '2BHK', sqft: 1200, facing: 'West', status: 'Available', constructionStage: 'Structure', qualityDefects: 'No Issues', basePrice: 18500000 },
];

const STATUS_STYLES: Record<InventoryStatus, string> = {
  Available: 'bg-emerald-100 text-emerald-700 border border-emerald-200',
  Booked:    'bg-red-100 text-red-600 border border-red-200',
  Reserved:  'bg-yellow-100 text-yellow-700 border border-yellow-200',
  Blocked:   'bg-gray-100 text-gray-600 border border-gray-200',
};

const STATUS_DOT: Record<InventoryStatus, string> = {
  Available: 'bg-emerald-500',
  Booked:    'bg-red-500',
  Reserved:  'bg-yellow-500',
  Blocked:   'bg-gray-400',
};

const INVENTORY_FILTERS: InventoryStatus[] = ['Available', 'Booked', 'Reserved', 'Blocked'];

const formatCrore = (n: number) => {
  const cr = n / 10000000;
  return `₹${cr.toFixed(2)}Cr`;
};

// ── Sub-components ─────────────────────────────────────────────────────
function StatCard({ label, value, sub, accent, icon }: {
  label: string; value: string | number; sub: string; accent?: string; icon?: React.ReactNode;
}) {
  return (
    <div className="flex-1 min-w-0 px-6 py-4 border-r border-gray-200 last:border-r-0">
      {accent && (
        <div className={`flex items-center gap-1.5 mb-1`}>
          <span className={`w-2 h-2 rounded-full ${accent}`} />
          <span className="text-[10px] font-bold uppercase tracking-widest text-gray-500">{label}</span>
        </div>
      )}
      {!accent && (
        <p className="text-[10px] font-bold uppercase tracking-widest text-gray-500 mb-1">{label}</p>
      )}
      <p className="text-2xl font-black text-gray-900 leading-none">{value}</p>
      <p className="text-xs text-gray-400 mt-0.5">{sub}</p>
    </div>
  );
}

function StatusBadge({ status }: { status: InventoryStatus }) {
  return (
    <span className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-semibold ${STATUS_STYLES[status]}`}>
      <span className={`w-1.5 h-1.5 rounded-full ${STATUS_DOT[status]}`} />
      {status}
    </span>
  );
}

const pageHeader = {
  title: 'Property Inventory',
  breadcrumb: [
    { href: routes.dashboard, name: 'Home' },
    { name: 'Property Management' },
  ],
};

// ── Main Page ──────────────────────────────────────────────────────────
export default function Page() {
  const { openDrawer } = useDrawer();

  const [units, setUnits] = useState<Unit[]>(INITIAL_UNITS);
  const [search, setSearch] = useState('');
  const [statusFilter, setStatusFilter] = useState<InventoryStatus | 'All'>('All');
  const [bhkFilter, setBhkFilter] = useState('All Configurations (3)');
  const [facingFilter, setFacingFilter] = useState('All Facings (4)');
  const [milestoneFilter, setMilestoneFilter] = useState('All Milestones (3)');
  const [minPrice, setMinPrice] = useState('');
  const [maxPrice, setMaxPrice] = useState('');
  const [deleteItem, setDeleteItem] = useState<Unit | null>(null);
  const [selectedWing, setSelectedWing] = useState('Wing A');

  // Derived stats
  const available = units.filter(u => u.status === 'Available').length;
  const handover = units.filter(u => u.constructionStage === 'Handover').length;
  const totalRevenue = units.reduce((s, u) => s + u.basePrice, 0);

  const filtered = useMemo(() => {
    return units.filter(u => {
      if (statusFilter !== 'All' && u.status !== statusFilter) return false;
      if (search && !u.unitNum.toLowerCase().includes(search.toLowerCase()) &&
          !u.bhk.toLowerCase().includes(search.toLowerCase())) return false;
      if (minPrice && u.basePrice < Number(minPrice)) return false;
      if (maxPrice && u.basePrice > Number(maxPrice)) return false;
      return true;
    });
  }, [units, statusFilter, search, minPrice, maxPrice]);

  const occupancyPct = Math.round(((units.length - available) / units.length) * 100);

  const handleAdd = (data: any) => {
    setUnits(prev => [...prev, { ...data, id: Date.now(), qualityDefects: 'No Issues' }]);
  };

  const handleDelete = () => {
    if (!deleteItem) return;
    setUnits(prev => prev.filter(u => u.id !== deleteItem.id));
    setDeleteItem(null);
  };

  const wingOptions = [
    { value: "Wing A", label: "Wing A" },
    { value: "Wing B", label: "Wing B" },
    { value: "Wing C", label: "Wing C" },
  ];

  const projectOptions = [
    { value: "Galaxy Heights", label: "Galaxy Heights" },
  ];

  const bhkOptions = [
    { value: "all", label: "All Configurations (3)" },
    { value: "2BHK", label: "2BHK" },
    { value: "3BHK", label: "3BHK" },
    { value: "4BHK", label: "4BHK" },
  ];

  const facingOptions = [
    { value: "all", label: "All Facings (4)" },
    { value: "East", label: "East" },
    { value: "West", label: "West" },
    { value: "North", label: "North" },
    { value: "South", label: "South" },
  ];

  const milestoneOptions = [
    { value: "all", label: "All Milestones (3)" },
    { value: "Foundation", label: "Foundation" },
    { value: "Structure", label: "Structure" },
    { value: "Finishing", label: "Finishing" },
    { value: "Handover", label: "Handover" },
  ];

  const groupedByFloor = useMemo(() => {
    const groups: Record<string, Unit[]> = {};

    filtered.forEach((unit) => {
      const floor = unit.unitNum.split('-')[1]?.[0] || '0'; // A-201 → 2
      if (!groups[floor]) groups[floor] = [];
      groups[floor].push(unit);
    });

    // sort floors DESC (top → bottom like UI)
    return Object.entries(groups).sort((a, b) => Number(b[0]) - Number(a[0]));
  }, [filtered]);

  const renderIcons = (status: InventoryStatus) => {
    switch (status) {
      case 'Booked':
        return (
          <>
            <PiUser className='font-bolder text-gray-700 text-sm'/>
            <PiLock className='font-bolder text-red-600 text-sm'/>
          </>
        );
      case 'Reserved':
        return (
          <>
            <PiUser className='font-bolder text-gray-700 text-sm'/>
            <PiClock className='font-bolder text-yellow-600 text-sm'/>
          </>
        );
      default:
        return null;
    }
  };

  return (
    <>
      <TableLayout
        title={pageHeader.title}
        breadcrumb={pageHeader.breadcrumb}
        data={[]}
        fileName="property_inventory"
        header="Module,Add,Edit,Delete,View"
        showExport={false}
        showImport={false}
        actions={
          <div className='flex items-center gap-2 justify-end'>
            <button
              onClick={() => openDrawer({ view: <PropertyDrawer onSubmit={handleAdd} /> })}
              className="flex items-center gap-2 bg-primary text-white text-sm font-semibold px-4 py-2 rounded-lg shadow hover:opacity-90 transition"
            >
              <PiPlusBold size={15} />
              Add Unit
            </button>
            <ViewToggle
              views={[
                { label: 'Visual Stack', path: '/property_stack_view', icon: PiStack },
                { label: 'Card Grid', path: '/property_card', icon: PiGridFour },
                { label: 'Details List', path: '/manage_property', icon: PiListBullets },
              ]}
            />
          </div>
        }
      >
        <div className="grid grid-cols-12 gap-3 min-h-[calc(100vh-160px)]">
          <div className="col-span-3 border border-gray-200 rounded-lg bg-white shadow-sm flex flex-col">
            <div className="px-4 py-2">
              <label className="text-xs font-bold uppercase tracking-widest text-gray-400 mb-1.5 flex items-center gap-1">
                <PiBuildings size={14} /> Active Site Project
              </label>
              <Select
                options={projectOptions}
                defaultValue={projectOptions[0]}
                className="text-sm"
                classNamePrefix="react-select"
                isSearchable={false}
              />
            </div>

            <div className="px-4 py-3 border-b border-gray-100">
              <label className="text-xs font-bold uppercase tracking-widest text-gray-400 mb-1.5 flex items-center gap-1">
                <PiStack size={14} /> Tower Block / Wing
              </label>
              <Select
                options={wingOptions}
                value={wingOptions.find(opt => opt.value === selectedWing)}
                onChange={(selected) => setSelectedWing(selected?.value || "")}
                className="text-sm"
                classNamePrefix="react-select"
                isSearchable={false}
              />
            </div>
            <div className="px-4 py-3 flex-1 overflow-y-auto space-y-4">
              <div className="flex items-center justify-between">
                <span className="text-xs font-bold uppercase tracking-widest text-gray-400 flex items-center gap-1">
                  <PiFunnel size={14} /> Filter Criteria
                </span>
                <button
                  onClick={() => { setStatusFilter('All'); setSearch(''); setMinPrice(''); setMaxPrice(''); }}
                  className="text-xs text-primary font-semibold hover:underline"
                >
                  Reset All
                </button>
              </div>

              <div>
                <p className="text-xs text-gray-500 font-medium mb-2">Inventory Status</p>
                <div className="grid grid-cols-2 gap-1.5">
                  {(['All', ...INVENTORY_FILTERS] as const).map(s => (
                    <button
                      key={s}
                      onClick={() => setStatusFilter(s)}
                      className={`text-xs px-2 py-1.5 rounded-md border font-medium transition ${
                        statusFilter === s
                          ? 'bg-primary text-white border-primary'
                          : 'bg-white text-gray-600 border-gray-200 hover:border-primary/40'
                      }`}
                    >
                      {s}
                    </button>
                  ))}
                </div>
              </div>
              <div>
                <label className="text-xs text-gray-500 font-medium mb-1.5">Unit Layout / BHK</label>
                <Select
                  options={bhkOptions}
                  value={bhkOptions.find(opt => opt.value === bhkFilter)}
                  onChange={(selected) => setBhkFilter(selected?.value || "all")}
                  isSearchable={false}
                />
              </div>
              <div>
                <label className="text-xs text-gray-500 font-medium mb-1.5 flex items-center gap-1">
                  Vasthu / Facing
                </label>
                <Select
                  options={facingOptions}
                  value={facingOptions.find(opt => opt.value === facingFilter)}
                  onChange={(selected) => setFacingFilter(selected?.value || "all")}
                  isSearchable={false}
                />
              </div>
              <div>
                <label className="text-xs text-gray-500 font-medium mb-1.5">Construction Milestone</label>
                <Select
                  options={milestoneOptions}
                  value={milestoneOptions.find(opt => opt.value === milestoneFilter)}
                  onChange={(selected) => setMilestoneFilter(selected?.value || "all")}
                  isSearchable={false}
                />
              </div>
              <div>
                <p className="text-xs text-gray-500 font-medium mb-1.5">Base Price Range (INR)</p>
                <div className="flex items-center gap-1.5">
                  <input
                    type="number"
                    placeholder="Min ₹"
                    value={minPrice}
                    onChange={e => setMinPrice(e.target.value)}
                    className="w-full text-xs border border-gray-200 rounded-lg px-2.5 py-2 focus:outline-none"
                  />
                  <span className="text-gray-400 text-xs">-</span>
                  <input
                    type="number"
                    placeholder="Max ₹"
                    value={maxPrice}
                    onChange={e => setMaxPrice(e.target.value)}
                    className="w-full text-xs border border-gray-200 rounded-lg px-2.5 py-2 focus:outline-none"
                  />
                </div>
              </div>
            </div>
            <div className="px-4 py-3 border-t border-gray-100">
              <p className="text-[10px] font-bold uppercase tracking-widest text-gray-400 mb-2 flex items-center gap-1">
                <PiChartBar size={11} /> Wing Inventory Progress
              </p>
              <div className="flex justify-between items-center mb-1">
                <span className="text-xs text-gray-600">Occupancy Rate</span>
                <span className="text-xs font-bold text-primary">{occupancyPct}%</span>
              </div>
              <div className="w-full h-2 rounded-full bg-gray-100 overflow-hidden">
                <div
                  className="h-full rounded-full bg-primary transition-all duration-500"
                  style={{ width: `${occupancyPct}%` }}
                />
              </div>
              <div className="flex justify-between mt-1">
                <span className="text-[10px] text-gray-400">{units.length - available} Booked/Reserved</span>
                <span className="text-[10px] text-gray-400">{units.length} total units</span>
              </div>
            </div>
          </div>
          <div className="col-span-9 border border-gray-200 rounded-lg bg-gray-50 flex flex-col min-w-0">
            <div className="bg-white border-b border-gray-200 px-6 py-4 rounded-tr-xl">
              <div className="flex items-start justify-between gap-4">
                <div>
                  <div className="flex items-center gap-2 mb-0.5">
                    <span className="text-xs font-semibold text-gray-400 uppercase tracking-wider">Bandra West, Mumbai</span>
                    <span className="text-gray-300">•</span>
                    <span className="text-xs font-semibold text-primary uppercase tracking-wider">Under Construction</span>
                  </div>
                  <div className="flex items-center gap-3">
                    <h1 className="text-lg font-semibold text-gray-900">Property Inventory Dashboard</h1>
                    <span className="bg-blue-100 text-blue-700 text-xs font-bold px-2.5 py-0.5 rounded-full">{selectedWing}</span>
                  </div>
                </div>
                <div className="flex items-center gap-2 flex-shrink-0">
                  <button className="flex items-center gap-1.5 text-xs font-medium text-gray-600 border border-gray-200 rounded-lg px-3 py-1.5 bg-white hover:bg-gray-50 transition">
                    <PiExport size={13} /> Export CSV
                  </button>
                </div>
              </div>
            </div>
            <div className="bg-white border-b border-gray-200 flex">
              <StatCard
                label="Filtered Units"
                value={`${filtered.length} / ${units.length} tower total`}
                sub=""
                accent=""
              />
              <StatCard
                label="Available Stock"
                value={available}
                sub={`${available} units ready`}
                accent="bg-emerald-500"
              />
              <StatCard
                label="Immediate Handover"
                value={handover}
                sub="ready-to-move"
                accent="bg-blue-500"
              />
              <div className="flex-1 px-6 py-4">
                <p className="text-[10px] font-bold uppercase tracking-widest text-gray-500 mb-1">Unrealized Revenue Value</p>
                <p className="text-2xl font-black text-gray-900">
                  ₹{(totalRevenue / 10000000).toFixed(2)}
                  <span className="text-sm font-semibold text-gray-400 ml-1">Cr value</span>
                </p>
              </div>
            </div>
            <div className="p-4 space-y-4">
              {groupedByFloor.map(([floor, units]) => (
                <div
                  key={floor}
                  className="flex gap-4 items-stretch bg-white border rounded-xl p-0"
                >
                  <div className="w-20 flex-shrink-0 bg-gray-900 text-white rounded-s-lg flex flex-col items-center justify-center">
                    <span className="text-[10px] uppercase text-gray-300">Floor</span>
                    <span className="text-xl font-bold">{floor}</span>
                  </div>
                  <div className="flex gap-4 flex-wrap p-4">
                    {units.map((unit) => {
                      const statusStyle =
                        unit.status === 'Available'
                          ? 'border-emerald-400 bg-emerald-50'
                          : unit.status === 'Booked'
                          ? 'border-red-400 bg-red-50'
                          : unit.status === 'Reserved'
                          ? 'border-yellow-400 bg-yellow-50'
                          : 'border-gray-300 bg-gray-50';

                      return (
                        <div
                          key={unit.id}
                          className={`min-w-[220px] rounded-xl border p-4 ${statusStyle}`}onClick={() =>
                              openDrawer({
                                view: <UnitSpecDrawer unit={unit} />,
                              containerClassName: 'min-w-[480px] max-w-[480px]',
                            })
                          }
                        >
                          <h3 className="font-bold text-lg text-gray-900">
                            {unit.unitNum}
                          </h3>
                          <span className="text-xs text-gray-600 mt-1">
                            {unit.bhk} • {unit.sqft} SQFT • {unit.facing.toUpperCase()}
                          </span>
                          <div className="flex justify-between gap-5 items-center mt-2">
                            <span className="text-sm font-bold text-gray-900">
                              ₹{(unit.basePrice / 100000).toFixed(1)}L
                            </span>
                            <div className="flex items-center justify-end gap-2">
                              {renderIcons(unit.status)}
                            </div>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </TableLayout>

      <ConfirmModal
        open={!!deleteItem}
        onClose={() => setDeleteItem(null)}
        onConfirm={handleDelete}
        title="Delete Unit"
        description={`Are you sure you want to delete unit "${deleteItem?.unitNum}"?`}
      />
    </>
  );
}