import { useState, useRef } from 'react';
import {
  Title, Table, Group, Button, Stack, TextInput, Modal,
  Select, Badge, ActionIcon, Text, Loader, Center, Tooltip, Alert,
} from '@mantine/core';
import { useForm } from '@mantine/form';
import { useDisclosure } from '@mantine/hooks';
import { notifications } from '@mantine/notifications';
import { IconPlus, IconEdit, IconSearch, IconTrash, IconInfoCircle, IconUpload, IconDownload } from '@tabler/icons-react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import api from '../../services/api';
import { parseCSV, downloadBlob } from '../../utils/csv';

interface Unit {
  id: string;
  unit_number: string;
  address_line1: string;
  owner_name: string;
  owner_email: string;
  monthly_assessment: string;
  status: string;
  balance_due?: string;
  assessment_group_id?: string;
  assessment_group_name?: string;
  group_regular_assessment?: string;
  group_special_assessment?: string;
  group_frequency?: string;
}

interface AssessmentGroup {
  id: string;
  name: string;
  regular_assessment: string;
  frequency: string;
  is_default: boolean;
}

export function UnitsPage() {
  const [opened, { open, close }] = useDisclosure(false);
  const [editing, setEditing] = useState<Unit | null>(null);
  const [search, setSearch] = useState('');
  const [deleteConfirm, setDeleteConfirm] = useState<Unit | null>(null);
  const queryClient = useQueryClient();
  const fileInputRef = useRef<HTMLInputElement>(null);

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

  const { data: assessmentGroups = [] } = useQuery<AssessmentGroup[]>({
    queryKey: ['assessment-groups'],
    queryFn: async () => { const { data } = await api.get('/assessment-groups'); return data; },
  });

  const defaultGroup = assessmentGroups.find(g => g.is_default);
  const hasGroups = assessmentGroups.length > 0;

  const form = useForm({
    initialValues: {
      unit_number: '', address_line1: '', city: '', state: '', zip_code: '',
      owner_name: '', owner_email: '', owner_phone: '',
      assessment_group_id: '' as string | null,
    },
    validate: {
      unit_number: (v) => (v.length > 0 ? null : 'Required'),
      assessment_group_id: (v) => (v && v.length > 0 ? null : 'Assessment group is required'),
    },
  });

  const saveMutation = useMutation({
    mutationFn: (values: any) => {
      const payload = { ...values, assessment_group_id: values.assessment_group_id || null };
      return editing ? api.put(`/units/${editing.id}`, payload) : api.post('/units', payload);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['units'] });
      notifications.show({ message: editing ? 'Unit updated' : 'Unit created', color: 'green' });
      close(); setEditing(null); form.reset();
    },
    onError: (err: any) => { notifications.show({ message: err.response?.data?.message || 'Error', color: 'red' }); },
  });

  const deleteMutation = useMutation({
    mutationFn: (id: string) => api.delete(`/units/${id}`),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['units'] });
      notifications.show({ message: 'Unit deleted', color: 'green' });
      setDeleteConfirm(null);
    },
    onError: (err: any) => {
      notifications.show({ message: err.response?.data?.message || 'Cannot delete unit', color: 'red' });
      setDeleteConfirm(null);
    },
  });

  const importMutation = useMutation({
    mutationFn: async (rows: Record<string, string>[]) => {
      const { data } = await api.post('/units/import', rows);
      return data;
    },
    onSuccess: (data) => {
      queryClient.invalidateQueries({ queryKey: ['units'] });
      let msg = `Imported: ${data.created} created, ${data.updated} updated`;
      if (data.errors?.length) msg += `. ${data.errors.length} error(s): ${data.errors.slice(0, 3).join('; ')}`;
      notifications.show({ message: msg, color: data.errors?.length ? 'yellow' : 'green', autoClose: 10000 });
    },
    onError: (err: any) => { notifications.show({ message: err.response?.data?.message || 'Import failed', color: 'red' }); },
  });

  const handleEdit = (u: Unit) => {
    setEditing(u);
    form.setValues({
      unit_number: u.unit_number, address_line1: u.address_line1 || '',
      city: '', state: '', zip_code: '', owner_name: u.owner_name || '',
      owner_email: u.owner_email || '', owner_phone: '',
      assessment_group_id: u.assessment_group_id || '',
    });
    open();
  };

  const handleNew = () => {
    setEditing(null);
    form.reset();
    if (defaultGroup) form.setFieldValue('assessment_group_id', defaultGroup.id);
    open();
  };

  const handleExport = async () => {
    try {
      const response = await api.get('/units/export', { responseType: 'blob' });
      downloadBlob(response.data, 'units.csv');
    } catch { notifications.show({ message: 'Export failed', color: 'red' }); }
  };

  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = (e) => {
      const text = e.target?.result as string;
      if (!text) { notifications.show({ message: 'Could not read file', color: 'red' }); return; }
      const rows = parseCSV(text);
      if (!rows.length) { notifications.show({ message: 'No data rows found', color: 'red' }); return; }
      importMutation.mutate(rows);
    };
    reader.readAsText(file);
    event.target.value = '';
  };

  const filtered = units.filter((u) =>
    !search || u.unit_number.toLowerCase().includes(search.toLowerCase()) ||
    (u.owner_name || '').toLowerCase().includes(search.toLowerCase())
  );

  if (isLoading) return <Center h={300}><Loader /></Center>;

  return (
    <Stack>
      <Group justify="space-between">
        <Title order={2}>Units / Homeowners</Title>
        <Group>
          <Button variant="light" leftSection={<IconDownload size={16} />} onClick={handleExport} disabled={units.length === 0}>
            Export CSV
          </Button>
          <Button variant="light" leftSection={<IconUpload size={16} />} onClick={() => fileInputRef.current?.click()}
            loading={importMutation.isPending}>
            Import CSV
          </Button>
          <input type="file" ref={fileInputRef} accept=".csv,.txt" style={{ display: 'none' }} onChange={handleFileChange} />
          {hasGroups ? (
            <Button leftSection={<IconPlus size={16} />} onClick={handleNew}>Add Unit</Button>
          ) : (
            <Tooltip label="Create an assessment group first">
              <Button leftSection={<IconPlus size={16} />} disabled>Add Unit</Button>
            </Tooltip>
          )}
        </Group>
      </Group>

      {!hasGroups && (
        <Alert icon={<IconInfoCircle size={16} />} color="yellow" variant="light">
          You must create at least one assessment group before adding units. Go to Assessment Groups to create one.
        </Alert>
      )}

      <TextInput placeholder="Search units..." leftSection={<IconSearch size={16} />} value={search} onChange={(e) => setSearch(e.currentTarget.value)} />
      <Table striped highlightOnHover>
        <Table.Thead>
          <Table.Tr>
            <Table.Th>Unit #</Table.Th>
            <Table.Th>Address</Table.Th>
            <Table.Th>Owner</Table.Th>
            <Table.Th>Email</Table.Th>
            <Table.Th>Group</Table.Th>
            <Table.Th ta="right">Assessment</Table.Th>
            <Table.Th ta="right">Special Assessment</Table.Th>
            <Table.Th>Status</Table.Th>
            <Table.Th></Table.Th>
          </Table.Tr>
        </Table.Thead>
        <Table.Tbody>
          {filtered.map((u) => (
            <Table.Tr key={u.id}>
              <Table.Td fw={500}>{u.unit_number}</Table.Td>
              <Table.Td>{u.address_line1}</Table.Td>
              <Table.Td>{u.owner_name}</Table.Td>
              <Table.Td>{u.owner_email}</Table.Td>
              <Table.Td>
                {u.assessment_group_name ? (
                  <Badge variant="light" size="sm">{u.assessment_group_name}</Badge>
                ) : (
                  <Text size="xs" c="dimmed">-</Text>
                )}
              </Table.Td>
              <Table.Td ta="right" ff="monospace">
                ${parseFloat(u.group_regular_assessment || u.monthly_assessment || '0').toFixed(2)}
              </Table.Td>
              <Table.Td ta="right" ff="monospace">
                {parseFloat(u.group_special_assessment || '0') > 0
                  ? `$${parseFloat(u.group_special_assessment || '0').toFixed(2)}`
                  : <Text size="sm" c="dimmed">-</Text>
                }
              </Table.Td>
              <Table.Td><Badge color={u.status === 'active' ? 'green' : 'gray'} size="sm">{u.status}</Badge></Table.Td>
              <Table.Td>
                <Group gap={4}>
                  <ActionIcon variant="subtle" onClick={() => handleEdit(u)}>
                    <IconEdit size={16} />
                  </ActionIcon>
                  <Tooltip label="Delete unit">
                    <ActionIcon variant="subtle" color="red" onClick={() => setDeleteConfirm(u)}>
                      <IconTrash size={16} />
                    </ActionIcon>
                  </Tooltip>
                </Group>
              </Table.Td>
            </Table.Tr>
          ))}
          {filtered.length === 0 && <Table.Tr><Table.Td colSpan={9}><Text ta="center" c="dimmed" py="lg">No units yet</Text></Table.Td></Table.Tr>}
        </Table.Tbody>
      </Table>

      {/* Create/Edit Modal */}
      <Modal opened={opened} onClose={close} title={editing ? 'Edit Unit' : 'New Unit'} size="md">
        <form onSubmit={form.onSubmit((v) => saveMutation.mutate(v))}>
          <Stack>
            <TextInput label="Unit Number" required {...form.getInputProps('unit_number')} />
            <TextInput label="Address" {...form.getInputProps('address_line1')} />
            <Group grow>
              <TextInput label="City" {...form.getInputProps('city')} />
              <TextInput label="State" {...form.getInputProps('state')} />
              <TextInput label="ZIP" {...form.getInputProps('zip_code')} />
            </Group>
            <TextInput label="Owner Name" {...form.getInputProps('owner_name')} />
            <TextInput label="Owner Email" {...form.getInputProps('owner_email')} />
            <TextInput label="Owner Phone" {...form.getInputProps('owner_phone')} />
            <Select
              label="Assessment Group"
              description="Required — the unit's monthly assessment is inherited from the selected group"
              required
              data={assessmentGroups.map(g => ({
                value: g.id,
                label: `${g.name}${g.is_default ? ' (Default)' : ''} — $${parseFloat(g.regular_assessment || '0').toFixed(2)}/${g.frequency || 'mo'}`,
              }))}
              value={form.values.assessment_group_id}
              onChange={(v) => form.setFieldValue('assessment_group_id', v)}
              error={form.errors.assessment_group_id}
            />
            <Button type="submit" loading={saveMutation.isPending}>{editing ? 'Update' : 'Create'}</Button>
          </Stack>
        </form>
      </Modal>

      {/* Delete Confirmation Modal */}
      <Modal opened={!!deleteConfirm} onClose={() => setDeleteConfirm(null)} title="Delete Unit" size="sm">
        <Stack>
          <Text>
            Are you sure you want to delete unit <strong>{deleteConfirm?.unit_number}</strong>
            {deleteConfirm?.owner_name ? ` (${deleteConfirm.owner_name})` : ''}?
          </Text>
          <Text size="sm" c="dimmed">This action cannot be undone.</Text>
          <Group justify="flex-end">
            <Button variant="default" onClick={() => setDeleteConfirm(null)}>Cancel</Button>
            <Button
              color="red"
              loading={deleteMutation.isPending}
              onClick={() => deleteConfirm && deleteMutation.mutate(deleteConfirm.id)}
            >
              Delete
            </Button>
          </Group>
        </Stack>
      </Modal>
    </Stack>
  );
}
