import { useState, useEffect, useMemo, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import dayjs from 'dayjs';
import {
  Building2,
  UserPlus,
  Package,
  Handshake,
  History,
  PieChart,
  Layers,
  Users,
  ArrowRight,
  Calendar
} from 'lucide-react';
import { Button } from '@astryxdesign/core/Button';
import { Card } from '@astryxdesign/core/Card';
import { Table, proportional, pixel } from '@astryxdesign/core/Table';
import { Badge } from '@astryxdesign/core/Badge';
import { Text, Heading } from '@astryxdesign/core/Text';
import { Banner } from '@astryxdesign/core/Banner';

import PageHeader from '@/components/PageHeader';
import StatCard from '@/components/StatCard';
import StatusChip from '@/components/StatusChip';
import DonutChart from '@/components/charts/DonutChart';
import UserAvatar from '@/components/UserAvatar';
import EmptyState from '@/components/EmptyState';
import { fetchClients, fetchUsers } from '@/utils/apiClient';
import { toClient, toUser } from '@/utils/mappers';
import { titleCase } from '@/utils/format';

const STATUS_COLOR = { newclient: '#00A2AE', contacted: '#FFBF00', onboarded: '#00A854', lost: '#F04134' };
const statusColor = (s) => STATUS_COLOR[String(s || '').toLowerCase()] || '#8C8C8C';
const BAR_COLORS = ['#C01227', '#00A2AE', '#00A854', '#FFBF00', '#9E0E20', '#8C8C8C', '#D6515C'];

function Panel({ icon: Icon, title, action, color = 'primary', noPadding = false, children }) {
  return (
    <Card
      style={{
        height: '100%',
        display: 'flex',
        flexDirection: 'column',
        borderRadius: '16px',
        border: '1px solid rgba(5, 54, 89, 0.08)',
        backgroundColor: '#ffffff',
        overflow: 'hidden',
        boxShadow: '0 10px 30px -5px rgba(0,0,0,0.02), 0 4px 12px -3px rgba(0,0,0,0.02)',
        boxSizing: 'border-box'
      }}
    >
      <div
        style={{
          display: 'flex',
          flexDirection: 'row',
          alignItems: 'center',
          padding: '10px 16px',
          borderBottom: '1px solid rgba(5, 54, 89, 0.06)',
          background: 'linear-gradient(90deg, rgba(192, 18, 39, 0.03) 0%, rgba(255, 255, 255, 0) 100%)',
          gap: '10px',
          flexWrap: 'wrap'
        }}
      >
        <div
          style={{
            width: '30px',
            height: '30px',
            borderRadius: '7px',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            backgroundColor: 'rgba(192, 18, 39, 0.08)',
            color: '#C01227',
            flexShrink: 0
          }}
        >
          <Icon size={15} />
        </div>
        <div style={{ flexGrow: 1, minWidth: 0 }}>
          <Heading level={5}>{title}</Heading>
        </div>
        {action}
      </div>
      <div style={{ padding: noPadding ? '0' : '16px', flexGrow: 1, boxSizing: 'border-box' }}>
        {children}
      </div>
    </Card>
  );
}

export default function Dashboard() {
  const navigate = useNavigate();
  const [selectedDate, setSelectedDate] = useState(() => dayjs().format('YYYY-MM-DD'));
  const [clients, setClients] = useState([]);
  const [team, setTeam] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  // Guards against out-of-order responses (e.g. React StrictMode's double-invoked
  // effect) so a stale request can never clobber a newer one's result.
  const loadRequestId = useRef(0);

  const load = () => {
    const requestId = ++loadRequestId.current;
    setLoading(true);
    setError(null);
    Promise.all([fetchClients(), fetchUsers()])
      .then(([cs, us]) => {
        if (loadRequestId.current !== requestId) return;
        setClients((cs || []).map(toClient));
        setTeam((us || []).map(toUser));
      })
      .catch((e) => {
        if (loadRequestId.current === requestId) setError(e.message || 'Failed to load dashboard data');
      })
      .finally(() => {
        if (loadRequestId.current === requestId) setLoading(false);
      });
  };

  useEffect(() => { load(); }, []);

  const stats = useMemo(() => ({
    total: clients.length,
    newCount: clients.filter((c) => c.status === 'newClient').length,
    parcels: clients.reduce((s, c) => s + c.parcelVolume, 0),
    contracts: clients.reduce((s, c) => s + c.activeContracts, 0)
  }), [clients]);

  const statusData = useMemo(() => {
    const m = {};
    clients.forEach((c) => { m[c.status] = (m[c.status] || 0) + 1; });
    return Object.entries(m).sort((a, b) => b[1] - a[1]).map(([status, value]) => ({ label: titleCase(status), value, color: statusColor(status) }));
  }, [clients]);

  const byType = useMemo(() => {
    const m = {};
    clients.forEach((c) => { const t = c.businessType || 'other'; m[t] = (m[t] || 0) + 1; });
    return Object.entries(m).sort((a, b) => b[1] - a[1]);
  }, [clients]);
  const maxType = byType[0]?.[1] || 1;

  const recent = useMemo(
    () => [...clients].sort((a, b) => String(b.lastUpdated).localeCompare(String(a.lastUpdated))).slice(0, 6),
    [clients]
  );

  const recentColumns = useMemo(() => [
    {
      key: 'name',
      header: <div style={{ paddingLeft: '24px' }}>Client</div>,
      width: proportional(2),
      renderCell: (c) => (
        <div style={{ display: 'flex', alignItems: 'center', gap: '12px', paddingLeft: '24px' }}>
          <UserAvatar name={c.name} size={32} />
          <Text type="body" weight="semibold">{c.name}</Text>
        </div>
      )
    },
    {
      key: 'businessType',
      header: 'Type',
      width: proportional(1),
      renderCell: (c) => c.businessType
        ? <Badge variant="neutral" label={titleCase(c.businessType)} />
        : <Text type="supporting" color="disabled">—</Text>
    },
    {
      key: 'location',
      header: 'Location',
      width: proportional(1),
      renderCell: (c) => (
        <Text type="body">{`${c.city || '—'}${c.businessState ? `, ${c.businessState}` : ''}`}</Text>
      )
    },
    {
      key: 'parcelVolume',
      header: 'Parcels',
      width: pixel(110),
      align: 'end',
      renderCell: (c) => <Text type="body" weight="semibold" hasTabularNumbers>{c.parcelVolume.toLocaleString('en-IN')}</Text>
    },
    {
      key: 'status',
      header: 'Status',
      width: pixel(140),
      renderCell: (c) => <StatusChip status={c.status} />
    }
  ], []);

  const datePickerAction = (
    <input
      type="date"
      className="dashboard-date-picker"
      value={selectedDate}
      onChange={(e) => setSelectedDate(e.target.value)}
      style={{
        padding: '8px 12px',
        borderRadius: '10px',
        border: '1px solid rgba(5, 54, 89, 0.12)',
        fontSize: '0.875rem',
        fontWeight: 500,
        fontFamily: 'inherit',
        color: '#1e293b',
        backgroundColor: '#ffffff',
        outline: 'none',
        cursor: 'pointer',
        transition: 'all 0.2s ease',
        boxShadow: '0 1px 2px rgba(15, 23, 42, 0.04)',
        width: '150px'
      }}
      onFocus={(e) => {
        e.target.style.borderColor = '#C01227';
        e.target.style.boxShadow = '0 0 0 3px rgba(192, 18, 39, 0.12)';
      }}
      onBlur={(e) => {
        e.target.style.borderColor = 'rgba(5, 54, 89, 0.12)';
        e.target.style.boxShadow = '0 1px 2px rgba(15, 23, 42, 0.04)';
      }}
    />
  );

  if (loading) {
    return (
      <div style={{ fontFamily: 'system-ui, sans-serif' }}>
        <PageHeader title="Dashboard" action={datePickerAction} />
        <div style={{ display: 'flex', justifyContent: 'center', padding: '96px 0' }}>
          <div className="spinner" style={{ width: '40px', height: '40px', border: '4px solid #f1f5f9', borderTop: '4px solid #C01227', borderRadius: '50%', animation: 'spin 1s linear infinite' }} />
          <style>{`@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }`}</style>
        </div>
      </div>
    );
  }

  return (
    <div style={{ fontFamily: 'system-ui, sans-serif' }}>
      <PageHeader title="Dashboard" action={datePickerAction} />

      {error && (
        <div style={{ marginBottom: '24px' }}>
          <Banner
            status="error"
            title={error}
            endContent={<Button label="Retry" variant="ghost" size="sm" onClick={load} />}
          />
        </div>
      )}

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))', gap: '12px', marginBottom: '16px' }}>
        <StatCard size="sm" title="Total Clients" value={stats.total} icon={Building2} color="primary" />
        <StatCard size="sm" title="New Clients" value={stats.newCount} icon={UserPlus} color="info" />
        <StatCard size="sm" title="Total Parcel Volume" value={stats.parcels.toLocaleString('en-IN')} icon={Package} color="success" />
        <StatCard size="sm" title="Active Contracts" value={stats.contracts} icon={Handshake} color="warning" />
      </div>

      {/* Main dashboard panels */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr', gap: '16px', marginBottom: '16px' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr', lg: 'repeat(12, 1fr)', gap: '16px' }} className="responsive-row">
          {/* Recent Clients */}
          <div style={{ gridColumn: 'span 8' }} className="col-span-8">
            <Panel
              icon={History}
              title="Recent Clients"
              color="primary"
              noPadding
              action={recent.length > 0 && (
                <Button
                  label="View all"
                  variant="ghost"
                  size="sm"
                  icon={<ArrowRight size={14} />}
                  onClick={() => navigate('/clients')}
                />
              )}
            >
              {recent.length === 0 ? (
                <EmptyState icon={Building2} title="No clients yet" caption="Add a client under the Clients menu to see it here." />
              ) : (
                <div style={{ paddingTop: '8px', paddingBottom: '8px' }}>
                  <Table
                    data={recent}
                    columns={recentColumns}
                    idKey="id"
                    density="compact"
                    dividers="rows"
                    hasHover
                    isStriped
                    textOverflow="truncate"
                  />
                </div>
              )}
            </Panel>
          </div>

          {/* Clients by Status */}
          <div style={{ gridColumn: 'span 4' }} className="col-span-4">
            <Panel icon={PieChart} title="Clients by Status" color="primary">
              <div style={{ display: 'flex', justifyContent: 'center', padding: '4px 0' }}>
                {statusData.length === 0 ? (
                  <EmptyState icon={PieChart} title="No status breakdown" caption="No client status distribution available." />
                ) : (
                  <DonutChart data={statusData} size={140} thickness={20} centerValue={stats.total} centerLabel="Clients" />
                )}
              </div>
            </Panel>
          </div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr', lg: 'repeat(12, 1fr)', gap: '16px' }} className="responsive-row">
          {/* Business Type bar chart */}
          <div style={{ gridColumn: 'span 8' }} className="col-span-8">
            <Panel icon={Layers} title="Clients by Business Type" color="primary">
              {byType.length === 0 ? (
                <EmptyState icon={Layers} title="No business types" caption="No business type distribution available." />
              ) : (
                <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
                  {byType.map(([type, count], i) => (
                    <div key={type}>
                      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '4px' }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                          <div style={{ width: '10px', height: '10px', borderRadius: '3px', backgroundColor: BAR_COLORS[i % BAR_COLORS.length] }} />
                          <Text type="body" weight="semibold">{titleCase(type)}</Text>
                        </div>
                        <Text type="body" color="secondary" hasTabularNumbers>
                          {count} · {Math.round((count / clients.length) * 100)}%
                        </Text>
                      </div>
                      <div style={{ height: '6px', borderRadius: '3px', backgroundColor: '#f1f5f9', width: '100%', overflow: 'hidden' }}>
                        <div style={{ height: '100%', borderRadius: '3px', backgroundColor: BAR_COLORS[i % BAR_COLORS.length], width: `${(count / maxType) * 100}%` }} />
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </Panel>
          </div>

          {/* App Users */}
          <div style={{ gridColumn: 'span 4' }} className="col-span-4">
            <Panel
              icon={Users}
              title="App Users"
              color="primary"
            >
              {team.length === 0 ? (
                <EmptyState title="No team users" />
              ) : (
                <div style={{ display: 'flex', flexDirection: 'column' }}>
                  {team.slice(0, 6).map((u) => (
                    <div
                      key={u.id}
                      style={{
                        display: 'flex',
                        alignItems: 'center',
                        gap: '10px',
                        padding: '8px 12px',
                        margin: '1px -12px',
                        borderRadius: '10px',
                        transition: 'background-color 0.2s ease',
                        cursor: 'pointer'
                      }}
                      className="team-row-hover"
                    >
                      <UserAvatar name={u.name} size={30} />
                      <div style={{ flexGrow: 1, minWidth: 0 }}>
                        <Text type="body" weight="semibold" maxLines={1}>{u.name}</Text>
                        <Text type="supporting" color="secondary" maxLines={1}>{u.email}</Text>
                      </div>
                      <StatusChip status={u.role} />
                    </div>
                  ))}
                </div>
              )}
            </Panel>
          </div>
        </div>
      </div>

      <style>{`
        @media (min-width: 1024px) {
          .responsive-row {
            grid-template-columns: repeat(12, 1fr) !important;
          }
          .col-span-8 {
            grid-column: span 8 !important;
          }
          .col-span-4 {
            grid-column: span 4 !important;
          }
        }
        @media (max-width: 1023px) {
          .responsive-row {
            grid-template-columns: 1fr !important;
          }
          .col-span-8, .col-span-4 {
            grid-column: span 1 !important;
          }
        }
        
        /* Stat card hover transition effects */
        .stat-card {
          transition: transform 0.25s cubic-bezier(0.4, 0, 0.2, 1), box-shadow 0.25s cubic-bezier(0.4, 0, 0.2, 1), border-color 0.25s cubic-bezier(0.4, 0, 0.2, 1) !important;
        }
        .stat-card:hover {
          transform: translateY(-4px);
          box-shadow: 0 12px 28px rgba(15, 23, 42, 0.08) !important;
          border-color: rgba(192, 18, 39, 0.2) !important;
        }

        /* Team member row hover polish */
        .team-row-hover:hover {
          background-color: rgba(192, 18, 39, 0.04) !important;
        }
      `}</style>
    </div>
  );
}
